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个字符与S2前j个字符是否构成S3前i+j字符;[cpp] view plain copy
class Solution
{
public:
bool isInterleve(string s1, string s2, string s3)
{
int rows = s1.length();
int cols = s2.length();
int lens = s3.length();
if ((rows+cols)!=lens)
{
return false;
}
if (rows==0 || cols==0)
{
if ((rows==0 && s2!=s3)
|| (cols==0 && s1!=s3))
{
return false;
}
}
vector<vector<int>> dp(rows+1, vector<int>(cols+1, false));
dp[0][0] = true;
//初始化操作
for (int i=1; i<=rows; i++)
{
dp[i][0] = dp[i - 1][0] && (s1[i-1]==s3[i-1]);
}
for (int i = 1; i <= cols; i++)
{
dp[0][i] = dp[0][i] && (s2[i - 1] == s3[i - 1]);
}
for (int i=1; i<=rows; i++)
{
for (int j=1; j<=cols; j++)
{
//要满足条件,则s3的最后一个要么是s1的最后一个字符
//要么是s2的最后一个字符
if (s3[i + j - 1] == s1[i - 1] && dp[i - 1][j])
{
dp[i][j] = true;
}
else if (s3[i + j - 1] == s2[j - 1] && dp[i][j - 1])
{
dp[i][j] = true;
}
else
dp[i][j] = false;
}
}
return dp[rows][cols];
}
};