[LeetCode] Longest Word in Dictionary

720. Longest Word in Dictionary

Given an array of strings words representing an English Dictionary, return the longest word in words that can be built one character at a time by other words in words.

If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#define all(a) begin(a), end(a)
class Solution {
public:
string longestWord(vector<string>& words) {
sort(all(words), [](string& a, string& b){
if(a.length() == b.length())
return a < b;
return a.length() < b.length();
});
string res = "";
unordered_set<string> us{""};
for(auto& w : words) {
string pw = w;
pw.pop_back();
if(us.count(pw)) {
us.insert(w);
if(res.length() < w.length()) {
res = w;
}
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/12/PS/LeetCode/longest-word-in-dictionary/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.