如果你想在校招中顺利拿到更好的offer,阿秀建议你多看看前人的经验 ,比如准备 、简历 、实习 、上岸经历 、校招总结 、阿里、字节、腾讯、美团等一二线大厂真实面经 、也欢迎来一起参加秋招打卡活动 等;如果你是计算机小白,学习/转行/校招路上感到迷茫或者需要帮助,可以点此联系阿秀;免费分享阿秀个人学习计算机以来的收集到的好资源,点此白嫖;如果你需要《阿秀的学习笔记》网站中求职相关知识点的PDF版本的话,可以点此下载
# 720. 词典中最长的单词
力扣原题链接(点我直达) (opens new window)
给出一个字符串数组words
组成的一本英语词典。从中找出最长的一个单词,该单词是由words
词典中其他单词逐步添加一个字母组成。若其中有多个可行的答案,则返回答案中字典序最小的单词。
若无答案,则返回空字符串。
示例 1:
输入:
words = ["w","wo","wor","worl", "world"]
输出: "world"
解释:
单词"world"可由"w", "wo", "wor", 和 "worl"添加一个字母组成。
1
2
3
4
5
2
3
4
5
示例 2:
输入:
words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
输出: "apple"
解释:
"apply"和"apple"都能由词典中的单词组成。但是"apple"得字典序小于"apply"。
1
2
3
4
5
2
3
4
5
注意:
- 所有输入的字符串都只包含小写字母。
words
数组长度范围为[1,1000]
。words[i]
的长度范围为[1,30]
。
# 第一版,看了提示,其实并没有什么窍门
执行用时 :44 ms, 在所有 cpp 提交中击败了99.73%的用户
内存消耗 :16.2 MB, 在所有 cpp 提交中击败了89.41%的用户
bool compareSize(const string& a, const string& b) {
if(a.size()!=b.size())
return a.size() < b.size();
else
{
return a > b;//当size一样时,字典序小的在后面,这一点很厉害
}
}
string longestWord(vector<string>& words) {
sort(words.begin(), words.end(), compareSize);
unordered_set<string> unst;
for (auto& a : words) {
unst.insert(a);
}
string result;
for (int i=words.size()-1; i >=0;--i) {//从后往前走
result = words[i];
int len = result.size();
while (len--) {
result.pop_back();
if (unst.find(result) == unst.end()) break;
}
if (len == 0) {
result = words[i];
break;
}
}
return result;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39