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 len1 = s1.length();
int len2 = s2.length();
int len3 = s3.length();
if( len1 == 0 && len2 == 0 && len3 == 0){
return true;
}
if(len3 != ( len1 + len2 )){
return false;
}
vector<bool> dp(len2+1);
for(size_t i = 0; i <= len1; ++i){
for(size_t j = 0; j <= len2; ++j){
if(i == 0){
if(j == 0){
dp[j] = true;
}else{
dp[j] = (dp[j-1] && (s2[j-1] == s3[i+j-1]));
}
}else{
if(j == 0){
dp[j] = (dp[j] && (s1[i-1] == s3[i+j-1]));
}else{
dp[j] = (dp[j] && s1[i-1] == s3[i+j-1]) || (dp[j-1] && s2[j-1] == s3[i+j-1]);
}
}
}
}
return dp[len2];
}
};