1,题目要求
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.
以字典序,找到可以组成的最长的字符串。
2,题目思路
因为给定的字符串序列是无序的,因此应该首先对整个字符串向量进行排序,这样题目的要求就基本完成了一办了。其次就是依次对字符串进行判断,看是否满足题设条件。
首先,如果该字符串的长度为1,或者该字符串的前n-1位在设定的set中出现过,那么就继续进行判断。
如果该字符串的长度比准备返回的字符串res长度要长,则对准备返回的字符串进行更新操作。
3,程序源码
class Solution {
public:
string longestWord(vector<string>& words) {
sort(words.begin(),words.end()); //按照字母顺序对向量里的元素进行排序
unordered_set<string> record;
string res;
for(string word : words)
{
if(word.size()==1 || record.count(word.substr(0,word.size()-1)))//长度为1或者含有长度为n-1子串的成员在set之中
{
if(word.size()>res.size()) //长度是不是变长了?
res = word;
record.insert(word);
}
}
return res;
}
};
首先,sort函数的排序是按照字典序进行排列的。
其次,因为要进行存在性的查询,因此要用到集合的特性,而且用到的是特殊的一种集合形式:
unordered_set
1,头文件为< unorder_set>
2,其次,该容器与普通set最大的不同就是,其中的元素是无序的,因此特点就是如果仅仅需要对元素值进行查询,速度上会快许多。