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) {
if (s1.size() + s2.size() != s3.size())
return false;
return matchOrNot(s1, 0, s2, 0, s3, 0);
}
bool matchOrNot(string &s1, int p1, string &s2, int p2, string &s3, int p3) {
if (p3 == s3.size())
return true;
if (p1 == s1.size())
return s2.substr(p2) == s3.substr(p3);
if (p2 == s2.size())
return s1.substr(p1) == s3.substr(p3);
if (s1[p1] == s3[p3] && s2[p2] == s3[p3])
return matchOrNot(s1, p1 + 1, s2, p2, s3, p3 + 1) || matchOrNot(s1, p1, s2, p2 + 1, s3, p3 + 1);
else if (s1[p1] == s3[p3])
return matchOrNot(s1, p1 + 1, s2, p2, s3, p3 + 1);
else if (s2[p2] == s3[p3])
return matchOrNot(s1, p1, s2, p2 + 1, s3, p3 + 1);
else
return false;
}
};
DP正解:
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
unsigned len1 = s1.size();
unsigned len2 = s2.size();
if (len1 + len2 != s3.size())
return false;
vector<vector<bool> > array(len1 + 1, vector<bool>(len2 + 1, false));
array[0][0] = true;
for (int i = 1; i < len1 + 1; ++i) {
if (s1[i - 1] == s3[i - 1])
array[i][0] = true;
else
break;
}
for (int j = 1; j < len2 + 1; ++j) {
if (s2[j - 1] == s3[j - 1])
array[0][j] = true;
else
break;
}
for (int i = 1; i < len1 + 1; ++i) {
for (int j = 1; j < len2 + 1; ++j) {
if (array[i - 1][j] && s1[i - 1] == s3[i + j - 1])
array[i][j] = true;
else if (array[i][j - 1] && s2[j - 1] == s3[i + j - 1])
array[i][j] = true;
}
}
return array[len1][len2];
}
};