97. 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.
动态规划的思想,字符串的拼凑这种题要想到动态规划这类方法。
result[i][j]存的是s1前j位和s2前i位能不能合理组装成s3前i+j位
if(s2[i-1]==s3[i+j-1] && result[i-1][j]==1)
result[i][j]=1;
if(s1[j-1]==s3[i+j-1] && result[i][j-1]==1)
result[i][j]=1;
result[i][j]存的是s1前j位和s2前i位能不能合理组装成s3前i+j位
if(s2[i-1]==s3[i+j-1] && result[i-1][j]==1)
result[i][j]=1;
if(s1[j-1]==s3[i+j-1] && result[i][j-1]==1)
result[i][j]=1;
class Solution {
public:
bool isInterleave(string s1, string s2, string s3)
{
int size1 = s1.size();
int size2 = s2.size();
if (size1 + size2 != s3.size())
return false;
if (size1 == 0)
{
return (s2 == s3);
}
else if(size2 == 0)
{
return (s1 == s3);
}
vector<vector<int>> result(size2 + 1, vector<int> (size1 + 1, 0));
result[0][0] = 1;
//result[i][j]存的是s1前j位和s2前i位能不能合理组装成s3前i+j位
for (int j = 1; j <= size1; j++) //预处理第一行 没有s2的情况
{
if (s1[j-1] == s3[j-1])
result[0][j] = 1;
else
break;
}
for (int i = 1; i <= size2; i++)
{
for (int j = 0; j <= size1; j++)
{
if (j == 0) //预处理第二行 没有s1的情况
{
if (s2[i-1] == s3[i-1] && result[i-1][0] == 1)
result[i][j] = 1;
}
else
{
if (s2[i-1] == s3[i+j-1] && result[i-1][j] == 1)
result[i][j] = 1;
if (s1[j-1] == s3[i+j-1] && result[i][j-1] == 1)
result[i][j] = 1;
}
}
}
return (result[size2][size1] == 1);
}
};