题目
给一个词典,找出其中所有最长的单词。
样例
在词典
{
"dog",
"google",
"facebook",
"internationalization",
"blabla"
}
中, 最长的单词集合为 ["internationalization"]
在词典
{
"like",
"love",
"hate",
"yes"
}
中,最长的单词集合为 ["like", "love", "hate"]
思路
用动态规划的思路解决
vector<string> s;
假设我已经求出了前i个单词的最长集合S(i);
用L(i)表示最长集合S(i)的单词长度;
求S(i + 1)则分为三种情况
if(L(i) > dictionary[i + 1].length) S(i + 1) = S(i);
else if(L(i) == dictionary[i + 1].length) S(i + 1) = S(i) + dictionary[i + 1];
else if(L(i) < dictionary[i + 1].length)
{
S(i + 1) = dictionary[i + 1];
}
C++代码
vector<string> longestWords(vector<string> &dictionary) { // write your code here vector<string> s; int i; s.push_back(dictionary[0]); int t; for(i = 1; i < dictionary.size(); ++i) { if(s[0].length() == dictionary[i].length()) s.push_back(dictionary[i]); else if(s[0].length() < dictionary[i].length()) { s.clear(); s.push_back(dictionary[i]); } } return s; }
时间: 2024-10-06 02:54:05