[LeetCode]720. Longest Word in Dictionary 解题报告(C++)
题目描述
Given a list of strings words
representing an English Dictionary, find 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.
Example 1:
Input:
words = ["w","wo","wor","worl", "world"]
Output: "world"
Explanation:
The word "world" can be built one character at a time by "w", "wo", "wor", and "worl".
Example 2:
Input:
words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
Output: "apple"
Explanation:
Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "apply".
Note:
All the strings in the input will only contain lowercase letters.
The length of words
will be in the range [1, 1000]
.
The length of words[i]
will be in the range [1, 30]
.
题目大意
- 给了一个字典. 是个字符串数组.
- 从单个字符开始拼,最长能组成什么单词? 中间生成的字符串也必须存在于该字典中.且当长度相同时.选择字母顺序最小的那个.
解题思路
方法1:
- 将所有的词典放进哈希表中.在查找的思想来做.
- 在查找的时候可以用BFS来做.
- 使用
queue
辅助,先将长度为1的单词找到出队. - 再作为基础增加 字符.看是否存在于字典中.
- 若存在将其入队. 并更新输出结果(若长度相等要选择字母顺序小的)
- 若不存在.还原至出队的状态.换字符添加.
代码实现:
class Solution1 {
public:
string longestWord(vector<string>& words) {
string res = "";
int maxLen = 0;
unordered_set<string> s(words.begin(), words.end());
queue<string> q;
for (auto word : words) {
if (word.size() == 1) {
q.push(word);
}
}
while (!q.empty()) {
string t = q.front(); q.pop();
if (t.size() > maxLen) {
maxLen = t.size();
res = t;
}
else if (t.size() == maxLen) {
res = min(t, res);
}
for (char c = 'a'; c <= 'z'; c++) {
t += c;
if (s.count(t)) q.push(t);
t.pop_back();
}
}
return res;
}
};
方法2:
leetcode
高分方法:- 对字符串数组进行排序. 得到的就是按字母顺序和长度顺序的字符串数组.
- 初始化一个空的
set
. - 遍历排序后的字典. 当长度为1 或者 某个字符串去掉最后一个字符后存在于set中.
- 则说明它是能构造的.
- 用它来更新结果.且将其加入
set
代码实现:
class Solution2 {
public:
string longestWord(vector<string>& words) {
string res = "";
unordered_set<string> s;
sort(words.begin(), words.end()); // 排序
for (auto word : words) {
// 若字符串长度为1 或 去掉最后一个字符出现在哈希表中.
if (word.size() == 1 || s.count(word.substr(0, word.size() - 1))) {
// 更新结果.
res = (word.size() > res.size() ? word : res);
s.insert(word);
}
}
return res;
}
};