Description
Example 1
‘Example 2
Note
Solution 1(C++)
class Solution {
public:
string longestWord(vector<string>& words) {
sort(words.begin(), words.end());
unordered_set<string> built;
string res;
for (string w : words) {
if (w.size() == 1 || built.count(w.substr(0, w.size() - 1))) {
res = w.size() > res.size() ? w : res;
built.insert(w);
}
}
return res;
}
};
算法分析
首先搞明白题目的意思。题目的意思就是要找到字典排序的一个字符串。这样的字符串可以利用其中的部分字符组成比他短的其他字符串。
该解法首先将vector进行了排序。这里还是要注意注意,因为,vector储存的是string。那么,这里使用sort函数排序,应该首先按照字符串长度从短到长排序,相同长度的字符串,根据字典顺序排序。那么这样处理之后,题目要找的答案应该就是排在后面的。
那么,从前往后遍历,如果当前字符串长度等于1.那么就直接将res更新为当前字符串。并且将当前字符串插入到built中。如果遇到后面的字符串,如果长度减一的字符串在built中有对应项。那么这时候就应该对res进行更新。
程序分析
首先要注意vector< string >sort函数排序后的结果。
然后要注意string.substr()函数的使用。这里接触到了string类型,有必要对该类型做一个比较系统的总结了。