题目
思路 模拟
先把words中的字符串放到哈希表里,再遍历words的每一个字符串,判断它从0开始的每一个子串是否存在于哈希表里。
代码
class Solution {
public:
string longestWord(vector<string>& words) {
int ans = -1;
unordered_set<string> set;
for(string word : words)
set.insert(word);
for(int i = 0; i < words.size(); i++){
if(ans == -1 || words[ans].size() < words[i].size() || (words[ans].size() == words[i].size() && words[ans] > words[i])){
bool flag = true;
for(int j = 1; j < words[i].size(); j++){
if(set.count(words[i].substr(0,j)) == 0)
flag = false;
}
if(flag) ans = i;
}
}
return ans == -1 ? "" : words[ans];
}
};
思路 字典树
定义字典树数据结构,并定义insert和search方法,如果符合条件,每一位的isEnd都要是true才可以。
代码
class Trie{
private:
bool isEnd;
Trie* next[26];
public:
Trie(){
isEnd = false;
memset(next, 0, sizeof(next));
}
void insert(string word){
Trie* node = this;
for(char ch : word){
if(node -> next[ch - 'a'] == nullptr){
node -> next[ch - 'a'] = new Trie();
}
node = node -> next[ch - 'a'];
}
node -> isEnd = true;
}
bool search(string word){
Trie* node = this;
bool ans = false;
for(char ch : word){
node = node -> next[ch - 'a'];
if(node -> isEnd == false)
return false;
}
return true;
}
};
class Solution {
public:
string longestWord(vector<string>& words) {
string ans = "";
Trie* trie = new Trie();
for(string word : words)
trie -> insert(word);
for(string word : words){
if(ans.size() < word.size() || (ans.size() == word.size() && ans > word)){
if(trie -> search(word))
ans = word;
}
}
return ans;
}
};