您的位置:首页 > 职场人生

[LeetCode] Interleaving String

2014-01-04 02:24 363 查看
问题:

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.
分析:
可以用dp解决。建立一个二维的bool table,其中table[i][j]表示s1若只有前i个字符,s2若只有前j个字符的情况下,是不是interleaving。那么我们就有了:

table[i][j] = (s3[i+j-1] == s1[i-1] && table[i-1][j]) || (s3[i+j-1] == s2[j-1] && table[i][j-1])。

代码:(O(n^2))

class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
if (s3.size() != s1.size() + s2.size())
return false;
vector<vector<bool> > table (s1.size() + 1, vector<bool> (s2.size() + 1, false));
table[0][0] = true;
for (int i = 1; i <= s1.size(); i ++) {
if (s1[i-1] == s3[i-1])
table[i][0] = true;
else
break;
}
for (int i = 1; i <= s2.size(); i ++) {
if (s2[i-1] == s3[i - 1])
table[0][i] = true;
else
break;
}
for (int i = 1; i <= s1.size(); i ++) {
for (int j = 1; j <= s2.size(); j ++) {
int l = i + j;
if (s1[i - 1] == s3[l - 1])
table[i][j] = table[i][j] || table[i-1][j];
if (s2[j - 1] == s3[l - 1])
table[i][j] = table[i][j] || table[i][j-1];
}
}
return table[s1.size()][s2.size()];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 面试 leetcode