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.
使用动态规划,思路如下:
这是一个二维的动态规划,如s1长len1,s2长len2,建立一个(len1+1)*(len2+1)的bool数组,元素均初始化false
F[i][j]代表 s3[i+j-1] 与 s1[0]~s1[i-1]、s2[0]~s2[j] 或 s1[0]~s1[i]、s2[0]~s2[j-1] 是否满足题中条件,判断其为true还是false的条件就是 F[i-1][j] 为 true 且 s3[i-1+j] == s1[i-1],或者 F[i][j-1] 为 true 且 s3[i+j-1] == s2[j-1]。
true ; (i=0 && j=0)
F[i][j] = {
F[i-1][j] && (s1[i-1] == s3[i-1+j]) || F[i][j-1] && (s2[j-1] == s3[i+j-1]) ;(i>0 || j>0)
代码如下:
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
int len1 = s1.length(), len2 = s2.length(), len3 = s3.length();
if(len3 != len1+len2)
return false;
vector<vector<bool> >Tmp(len1+1, vector<bool>(len2+1, false));
//初始化Tmp[0][0]为true
bool tmp1 ,tmp2;
for(int i=0; i<=len1; ++i)
{
for(int j=0; j<=len2; ++j)
{
tmp1 = false;
tmp2 = false;
if(i == 0 && j == 0)
{
Tmp[i][j] = true;
continue;
}
if(i > 0)
tmp1 = Tmp[i-1][j] && (s1[i-1] == s3[i-1+j]);
if(j > 0)
tmp2 = Tmp[i][j-1] && (s2[j-1] == s3[i+j-1]);
Tmp[i][j] = tmp1 || tmp2;
}
}
return Tmp[len1][len2];
}
};