通过删除字母匹配到字典里最长单词

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
string findLongestWord(string s, vector<string>& dictionary) {
string ans;
for (int i = 0; i < dictionary.size(); i++) {
string& str = dictionary[i];
// 贪心法判断 str 是不是 s 的子序列
int j = 0, k = 0;
while (j < str.size() && k < s.size()) {
if (str[j] == s[k])
j++, k++;
else
k++;
}
if (j == str.size()) {
if (str.size() > ans.size() ||
(str.size() == ans.size() && str < ans)) {
ans = str;
}
}
}
return ans;
}
};