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.
参考 :http://www.2cto.com/kf/201305/215944.html
/* 分解成小问题,s3[0,i+j]的字符与s1[0,i],s[0,j]匹配,s3[0,i+j+1]的状态取决于s3[i+j+1] 与 s1[i+1]或者s2[0,j+1]是否匹配
isInterleaving(s1,len1,s2,len2,s3,len3)
= (s3.lastChar == s1.lastChar) && isInterleaving(s1,len1 - 1,s2,len2,s3,len3 - 1)
||(s3.lastChar == s2.lastChar) && isInterleaving(s1,len1,s2,len2 - 1,s3,len3 - 1)
*/
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
if(s3.size()!=s1.size()+s2.size())
return false;
if(s1.size()==0)
return s2==s3;
if(s2.size()==0)
return s1==s3;
vector<vector<bool>> flg(s1.size()+1,vector<bool>(s2.size()+1,false));
flg[0][0]=true;
for(int i=1;i<=s1.size();i++){
flg[i][0]=flg[i-1][0]&&(s1[i-1]==s3[i-1]);
}
for(int i=1;i<=s2.size();i++){
flg[0][i]=flg[0][i-1]&&(s2[i-1]==s3[i-1]);
}
for(int i=1;i<=s1.size();i++){
for(int j=1;j<=s2.size();j++){
flg[i][j]=( s1[i-1]==s3[i+j-1] && flg[i-1][j] ) || ( s2[j-1]==s3[i+j-1] && flg[i][j-1] );
}
}
return flg[s1.size()][s2.size()];
}
};