分类: C/C++
2014-09-17 09:38:44
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.
********************************************************************
分析:
f[i][j],表示s1[0, i]和s2[0, j],匹配s3[0, i + j]。如果s1的最后一个字符等于s3的最后一个字符,则f[i][j] = f[i - 1][j];如果s2的最后一个字符等于s3的最后一个字符,则f[i][j] = f[i][j - 1];
********************************************************************
代码:
bool isInterleave(string s1, string s2, string s3) {
if (s3.length() != s1.length() + s2.length())
return false;
vector
vector
for (size_t i = 1; i <= s1.length(); ++i)
f[i][0] = f[i - 1][0] && s1[i - 1] == s3[i - 1];
for (size_t i = 1; i <= s2.length(); ++i)
f[0][i] = f[0][i - 1] && s2[i - 1] == s3[i - 1];
for (size_t i = 1; i <= s1.length(); ++i)
for (size_t j = 1; j <= s2.length(); ++j)
f[i][j] = (s1[i - 1] == s3[i + j - 1] && f[i - 1][j])
|| (s2[j - 1] == s3[i + j - 1] && f[i][j - 1]);
return f[s1.length()][s2.length()];
}