法一:
遍历 dictionary 数组,取其字符串元素,记为 temp 与字符串 s 进行比较。
class Solution {
public:
string findLongestWord(string s, vector<string>& dictionary) {
int max = 0;
string res;
for(int i = 0; i < dictionary.size(); ++i) {
string temp = dictionary[i]; // 存放dictionary数组中第 i + 1 个字符串元素
// j指向temp中的第一个字符, k指向s中的第一个字符
int j = 0, k = 0;
while(j < temp.length() && k < s.length()) {
if(temp[j] == s[k]) ++j;
++k;
}
if(j >= temp.length()) { // 若可以通过s得到temp,则 j 大小等于temp的长度
if(j > max) {
max = j;
res = temp;
} else if(j == max && res > temp) {
res = temp;
}
}
}
return res;
}
};
法二:
使用 lambda 表达式结合 sort() 重新排序 dictionary 数组,使其按照字符串长度由大到小排序,如果长度相等,则按照字符串大小由小到大排序。
class Solution {
public:
string findLongestWord(string s, vector<string>& dictionary) {
// 排序 dictionary
sort(dictionary.begin(), dictionary.end(), [](string a, string b) {
if(a.length() != b.length()) return a.length() > b.length();
else return a < b;
});
// 从头遍历 dictionary 数组,直到找到第一个满足条件的数组元素为止
for(int i = 0; i < dictionary.size(); ++i) {
string temp = dictionary[i];
int j = 0, k = 0;
while(j < s.length() && k < temp.length()) {
if(s[j] == temp[k]) ++k;
++j;
}
if(k == temp.length()) return temp;
}
return "";
}
};