Skip to content

Commit b07d573

Browse files
committed
Add solution #720
1 parent 19544dc commit b07d573

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -301,6 +301,7 @@
301301
705|[Design HashSet](./0705-design-hashset.js)|Easy|
302302
706|[Design HashMap](./0706-design-hashmap.js)|Easy|
303303
713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium|
304+
720|[Longest Word in Dictionary](./0720-longest-word-in-dictionary.js)|Medium|
304305
722|[Remove Comments](./0722-remove-comments.js)|Medium|
305306
724|[Find Pivot Index](./0724-find-pivot-index.js)|Easy|
306307
733|[Flood Fill](./0733-flood-fill.js)|Easy|
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* 720. Longest Word in Dictionary
3+
* https://leetcode.com/problems/longest-word-in-dictionary/
4+
* Difficulty: Medium
5+
*
6+
* Given an array of strings words representing an English Dictionary, return the longest word
7+
* in words that can be built one character at a time by other words in words.
8+
*
9+
* If there is more than one possible answer, return the longest word with the smallest
10+
* lexicographical order. If there is no answer, return the empty string.
11+
*
12+
* Note that the word should be built from left to right with each additional character being
13+
* added to the end of a previous word.
14+
*/
15+
16+
/**
17+
* @param {string[]} words
18+
* @return {string}
19+
*/
20+
var longestWord = function(words) {
21+
const set = new Set();
22+
let result = '';
23+
24+
words.sort().forEach(word => {
25+
if (word.length === 1 || set.has(word.slice(0, -1))) {
26+
set.add(word);
27+
result = word.length > result.length ? word : result;
28+
}
29+
});
30+
31+
return result;
32+
};

0 commit comments

Comments
 (0)