Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:
s1 = "aabcc"
,
s2 = "dbbca"
,
When s3 = "aadbbcbcac"
, return true.
When s3 = "aadbbbaccc"
, return false.
这道题参考网上的答案写了解答,但是实际上还不是很懂。。估计多不久就又得忘了,不过还是把解法记录一下把。。
代码:
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
int l1=s1.length(),l2=s2.length(),l3=s3.length();
if(l1==0&&l2==0&&l3==0) return true;
if(l1==0){
if(s3==s2) return true;
else return false;
}
if(l2==0){
if(s3==s1) return true;
else return false;
}
if(l3!=l1+l2) return false;
//ans[i][j]表示s1的前i个字符和s2的前j个字符能否交替组成s3的前i+j个字符
vector<vector<bool> > ans(l1+1,vector<bool>(l2+1,false));
int i=0,j=0;
ans[0][0]=true;
for(;i<l1;i++){
if(s1[i]==s3[i]&&ans[i][0]) ans[i+1][0]=true;
}
for(;j<l2;j++){
if(s2[j]==s3[j]&&ans[0][j]) ans[0][j+1]=true;
}
for(i=1;i<=l1;i++){
for(j=1;j<=l2;j++){
if(s1[i-1]==s3[i+j-1]&&ans[i-1][j]) ans[i][j]=true;
if(s2[j-1]==s3[i+j-1]&&ans[i][j-1]) ans[i][j]=true;
}
}
return ans[l1][l2];
}
};