具体思想:
DP思路,直接双指针遍历判断是否相同,DP思路和最长子串相同;
没什么难点,就是自己脑子抽抽;
具体代码:
class Solution {
public:
int longestStrChain(vector<string>& words) {
sort(words.begin(),words.end(),[](string& a,string& b){
return a.size()<b.size();
});
int n=words.size();
int ret=1;
vector<int>dp(n,1);
for(int i=1;i<n;i++){
int maxn=1;
for(int j=0;j<i;j++){
if(words[j].size()!=words[i].size()-1||!charge(words[j], words[i]))
continue;
maxn=max(maxn,dp[j]+1);
}
dp[i]=maxn;
ret=max(ret,maxn);
}
return ret;
}
bool charge(string& a,string& b){
bool flag=false;
for(int i=0,j=0;i<a.size();){
if(a[i]!=b[j]){
if(flag)
return false;
flag=true;
j++;
continue;
}
i++,j++;
}
return true;
}
};