vector<string> longestWords(vector<string> &dictionary) {
// write your code here
vector<string> res;
int len=dictionary.size();
int max_len=0;
for(int i=0;i<len;i++)
{
if(max_len==dictionary[i].length())
res.push_back(dictionary[i]);
else if(max_len<dictionary[i].length())
{
res.clear();
max_len=dictionary[i].length();
res.push_back(dictionary[i]);
}
}
return res;
}
遍历两次的实现很容易想到,下面只说一下遍历一次注意的地方!
思路:遇见比当前长度长的字符串,res清零,重新添加,继续判断。