LeetCode 524. 双指针
原题链接
中等
作者:
史一帆
,
2021-04-28 20:58:50
,
所有人可见
,
阅读 270
class Solution {
public:
string findLongestWord(string s, vector<string>& dictionary) {
if (dictionary.size() == 0) return "";
string res = "";
for (auto sub : dictionary)
{
if (issubstr(s, sub) == true)
if (sub.size() > res.size() || sub.size() == res.size() && sub < res)
res = sub;
}
return res;
}
bool issubstr(string s, string dictionary)
{
int i, j;
for (i = 0, j = 0; i < s.size(); i ++ )
{
if (s[i] == dictionary[j]) j ++ ;
if (j == dictionary.size()) break;
}
if (j >= dictionary.size()) return true;
return false;
}
};
改进
class Solution {
public:
string findLongestWord(string s, vector<string>& dictionary) {
//if (dictionary.size() == 0) return "";
string res = "";
for (auto sub : dictionary)
{
if (issubstr(s, sub) == true)
if (sub.size() > res.size() || sub.size() == res.size() && sub < res)
res = sub;
}
return res;
}
bool issubstr(string s, string dictionary)
{
int i, j;
for (i = 0, j = 0; i < s.size(); i ++ )
if (s[i] == dictionary[j]) j ++ ;
return j == dictionary.size();
}
};