题目:
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 n1 = s1.size(), n2 = s2.size(), n3 = s3.size();
if (n1 + n2 != n3)
return false;
bool dp[1000][1000];
dp[0][0] = true;
for (int i = 1; i <= s1.size(); i++)
dp[i][0] = dp[i - 1][0] && s1[i - 1] == s3[i - 1];
for (int j = 1; j <= s2.size(); j++)
dp[0][j] = dp[0][j - 1] && s2[j - 1] == s3[j - 1];
for (int i = 1; i <= s1.size(); i++) {
for (int j = 1; j <= s2.size(); 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]);
}
return dp[n1][n2];
}
};