Skip to content

Commit ac945dd

Browse files
committed
solve problem Longest Word In Dictionary
1 parent c8d006b commit ac945dd

File tree

5 files changed

+59
-0
lines changed

5 files changed

+59
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,7 @@ All solutions will be accepted!
173173
|860|[LemonadeChange](https://leetcode-cn.com/problems/lemonade-change/description/)|[java/py/js](./algorithms/LemonadeChange)|Easy|
174174
|401|[Binary Watch](https://leetcode-cn.com/problems/binary-watch/description/)|[java/py/js](./algorithms/BinaryWatch)|Easy|
175175
|482|[License Key Formatting](https://leetcode-cn.com/problems/license-key-formatting/description/)|[java/py/js](./algorithms/LicenseKeyFormatting)|Easy|
176+
|720|[Longest Word In Dictionary](https://leetcode-cn.com/problems/longest-word-in-dictionary/description/)|[java/py/js](./algorithms/LongestWordInDictionary)|Easy|
176177

177178
# Database
178179
|#|Title|Solution|Difficulty|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Longest Word In Dictionary
2+
This problem is easy to solve by hashmap
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution {
2+
public String longestWord(String[] words) {
3+
String longestWord = null;
4+
Map<String, Boolean> wordsMap = new HashMap<String, Boolean>();
5+
6+
Arrays.sort(words);
7+
for (String word : words) {
8+
int length = word.length();
9+
if (length == 1 || wordsMap.get(word.substring(0, length - 1)) != null) {
10+
wordsMap.put(word, true);
11+
if (longestWord == null || longestWord.length() < length) {
12+
longestWord = word;
13+
}
14+
}
15+
}
16+
17+
return longestWord;
18+
}
19+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/**
2+
* @param {string[]} words
3+
* @return {string}
4+
*/
5+
var longestWord = function(words) {
6+
let longestWord = null,
7+
wordsMap = {}
8+
9+
words.sort().forEach(word => {
10+
if (word.length === 1 || wordsMap[word.slice(0, word.length - 1)]) {
11+
wordsMap[word] = true
12+
if (!longestWord || word.length > longestWord.length) {
13+
longestWord = word
14+
}
15+
}
16+
})
17+
return longestWord
18+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution(object):
2+
def longestWord(self, words):
3+
"""
4+
:type words: List[str]
5+
:rtype: str
6+
"""
7+
words.sort()
8+
9+
longest_word = None
10+
words_map = {}
11+
12+
for word in words:
13+
if len(word) == 1 or words_map.get(word[:-1]) != None:
14+
words_map[word] = True
15+
if not longest_word or len(word) > len(longest_word):
16+
longest_word = word
17+
18+
return longest_word
19+

0 commit comments

Comments
 (0)