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.empty()) return s2 == s3;
if (s2.empty()) return s1 == s3;
if (s1.length() + s2.length() != s3.length()) return false;
int l1 = s1.length();
int l2 = s2.length();
int l3 = s3.length();
vector<vector<int> > p(l1 + 1, vector<int>(l2 + 1, 0));
p[0][0] = true;
for (int i3 = 1; i3 <= l3; i3++)
{
for (int i1 = 0; i1 <= l1 && i1 < i3; i1++)
{
if (i3 - i1 - 1 > l2) continue;
if (p[i1][i3 - i1-1] && s2[i3 - i1 -1] == s3[i3-1])
p[i1][i3 - i1] = true;
if (p[i1][i3 - i1-1] && s1[i1] == s3[i3-1])
p[i1 + 1][i3- i1-1] = true;
}
}
return p[l1][l2];
}
};开始,二维动态数组我投机取巧用的是一个很大的临时变量bool[1000][1000],成功的掩饰了一个bug,就是越界条件的判断(代码中的continue),后来查询了一下二维动态数组用vector的方法,才使这个bug显现出来,加了continue语句后,成功通过。
684

被折叠的 条评论
为什么被折叠?



