题解
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class Solution {
private:
bool IsSubstr(string &s, string &t) {
int i = 0, j = 0;
while (i < s.size() && j < t.size()) {
//cout<<"bool:"<<s[i]<<t[j]<<endl;
if(s[i] == t[j]) {
++i;++j;
}
else ++i;
}
return j == t.size();
}
public:
string findLongestWord(string s, vector<string>& d) {
string str = "";
for (int i = 0; i < d.size(); ++i) {
//cout<<str.size()<<d[i].size()<<endl;;
if(str.size() < d[i].size() || (str.size() == d[i].size() && str.compare(d[i]) > 0)) {
if (IsSubstr(s, d[i])) {
str = d[i];
}
}
}
return str;
}
};
int main() {
Solution solution;
string s = "bab";
vector<string> d = {"ba", "ab"};
string result = solution.findLongestWord(s, d);
cout<<result<<endl;
return 0;
}
总结
字典序是指ascii码的顺序
"ab".compare("ba") = -1;
"ba".compare("ab") = 1;