0
点赞
收藏
分享

微信扫一扫

【Leetcode_easy】720. Longest Word in Dictionary

源码之路 2022-07-12 阅读 57
编程语言

problem

​​720. Longest Word in Dictionary​​

题意:

solution1: BFS;

class Solution {
public:
string longestWord(vector<string>& words) {
string res = "";
unordered_set<string> s(words.begin(), words.end());
queue<string> q;
for(auto word:words)
{
if(word.size()==1) q.push(word);
}
int maxLen = 0;
while(!q.empty())
{
string t = q.front();
q.pop();
if(t.size()>maxLen)
{
maxLen = t.size();
res = t;//err....
}
else if(t.size()==maxLen) res = min(res, t);
for(char ch='a'; ch<='z'; ++ch)//err...
{
t.push_back(ch);
if(s.count(t)) q.push(t);
t.pop_back();
}
}
return res;
}
};

solution2:

class Solution {
public:
string longestWord(vector<string>& words) {
string res = "";
unordered_set<string> s(words.begin(), words.end());
int maxLen = 0;
for (auto word:words)
{
if(word.size()==1) helper(s, word, maxLen, res);
}
return res;
}
void helper(unordered_set<string>& s, string word, int& maxLen, string& res) {
if(word.size()>maxLen)
{
maxLen = word.size();
res = word;
}
else if(word.size()==maxLen) res = min(res, word);
for(char ch = 'a'; ch<='z'; ++ch)
{
word.push_back(ch);
if(s.count(word)) helper(s, word, maxLen, res);
word.pop_back();
}
}
};

 

参考

1. ​​Leetcode_easy_720. Longest Word in Dictionary​​;

2. ​​Grandyang​​;

举报

相关推荐

0 条评论