问题:
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()];
}
};