Interleaving String
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.
采用动态规划,假设dp[i][j]表示了s1的前i个元素(包括第i个元素)s1[1],s1[2].....s1[i-1],与s2的前j个元素(包括第j个元素)s2[1],s2[2]...s2[j-1]是否可以构成s3
有两种情况可以考虑,
如果dp[i-1][j]成立了,且s1[i-1]==s3[i+j-1],那么可以认为dp[i][j]成立
如果dp[i][j-1]成立了,且s2[j-1]==s3[i+j-1],也可以认为dp[i][j]成立
所以可以得到如下的递推式:
dp[i][j]=(dp[i-1][j]&&s1[i-1]==s3[i+j-1])||(dp[i][j-1]&&s2[j-1]==s3[i+j-1]);
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) { int n1=s1.length();
int n2=s2.length();
int n3=s3.length(); if(n1+n2!=n3)
{
return false;
} vector<vector<bool> > dp(n1+,vector<bool>(n2+,false)); dp[][]=true; for(int i=;i<=n1;i++)
{
dp[i][]=dp[i-][]&&s1[i-]==s3[i-];
} for(int j=;j<=n2;j++)
{
dp[][j]=dp[][j-]&&s2[j-]==s3[j-];
} for(int i=;i<=n1;i++)
{
for(int j=;j<=n2;j++)
{
dp[i][j]=(dp[i-][j]&&s1[i-]==s3[i+j-])||(dp[i][j-]&&s2[j-]==s3[i+j-]);
}
} return dp[n1][n2];
}
};