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) {
// The length of s3 should be the sum of length of s1 and s2.
if (s1.length() + s2.length() != s3.length())
return false;
vector<vector<bool> > table(s1.length() + 1, vector<bool>(s2.length() + 1, false));
// Initialize the table for 动态规划
table[0][0] = true;
for(int ii = 1; ii <= s1.length(); ii++)
table[ii][0] = table[ii-1][0] && (s3[ii-1] == s1[ii-1]);
for(int jj = 1; jj <= s2.length(); jj++)
table[0][jj] = table[0][jj-1] && (s3[jj-1] == s2[jj-1]);
for(int ii = 1; ii <= s1.length(); ii ++)
for(int jj = 1; jj <= s2.length(); jj ++)
table[ii][jj] = (table[ii][jj - 1] && s2[jj - 1] == s3[ii + jj - 1]) || (table[ii - 1][jj] && s1[ii-1] == s3[ii + jj - 1]);
return table[s1.length()][s2.length()];
}
};