您的位置:首页 > 其它

【LeetCode】【97】Interleaving String

2015-03-13 11:28 441 查看
题目:

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.

解题报告:

这是一道字符串的问题,涉及到substring

所以自然而然想到dp.

类似于编辑距离等问题,一般两个字符串字串的问题,都是往二维矩阵来想。

令dp[i][j] 表示 s1(0~i-1) 与 s2(0~j-1)是否能够拼成s3(0~i+j-1)

从而构造了一个二维矩阵,然后思考其递推关系

可以发现,

dp[i][j] 只有当d[i-1][j]或者dp[i][j-1]为真,且增加相应的s1[i-1]或者s2[j-1]与s3[i+j-1]相等的时候,才为真,

于是便得到自底向上的递推关系。

代码如下:

class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
int len1 = s1.size();
int len2 = s2.size();
int len3 = s3.size();

if (len1 + len2 != len3)
return false;

vector<vector<bool>> dp(len1+1, vector<bool>(len2+1, false));

dp[0][0] = true;
for (int i=1; i<=len1; ++i)
if (s1[i-1] == s3[i-1])
dp[i][0] = true;

for (int i=1; i<=len2; ++i)
if (s2[i-1] == s3[i-1])
dp[0][i] = true;

for (int i=1; i<=len1; ++i)
{
for (int j = 1; j<=len2; ++j)
{
if (dp[i-1][j] == true && s1[i-1] == s3[i+j-1])
{
dp[i][j] = true;
continue;
}

if (dp[i][j-1] == true && s2[j-1] == s3[i+j-1])
{
dp[i][j] = true;
continue;
}
}
}

return dp[len1][len2];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: