今天这道题我们可以先判断字典里有多少子序列然后 进行比较看最终符合条件的有哪些
1.判断是否是子序列 与力扣392题相同
class Solution {
public:
bool isSubsequence(string s, string t) {
int n=s.size();
int m=t.size();
int i=0,j=0;
while(i<n && j<m){
if(s[i]==t[j]){
i++;
}
j++;
}
return i==n;
}
};
2.然后用临时变量比较存储 然后选择最终符合条件 //注意这里不是靠前而是整体删除靠前
class Solution {
public:
bool ifsonlist(string p,string q){
int m=p.size();
int n=q.size();
int i=0,j=0;
while(i<m && j<n){
if(p[i]==q[j]){
j++;
}
i++;
}
return j==n;
}
string findLongestWord(string s, vector<string>& dictionary) {
if(dictionary.size()==0) return " ";
int j=0;
int temp=0;//记录当前子序列长度
string ans="";//记当前答案;
for(auto d:dictionary){
if(ifsonlist(s,d)){
if(temp<d.size()){
temp=d.size();
ans=d;
}
else if(temp==d.size()){
ans=(ans<d)?ans:d;
}
}
}
return ans;
}
};