题目大意:求一个字符串s3是否由字符串s1和字符串s2的交叉组成的结果。
解题思路:动态规划。
用matched[i][j]表示s1的前i个字符串和s2的前j个字符串的交叉组合是否能成为s3的前i+j个字符串。
为了表述清楚,我们认为字符串的坐标是从1开始的,也就是第1个字符为字符串的头字符。
首先初始化
matched[0][j], s2的前j个字符串是否是s3的前j个字符串
matched[i][0], s1的前i个字符串是否是s3的前i个字符串。
然后:
当s1的前i - 1 个字符串和s3的前j个字符串交叉组成能成为s3的前i + j -1 时,
若s1(i)等于s3(i+j)时,matched[i][j] 为true.
当s1的前 i 个字符串和s3的前j - 1个字符串交叉组成能成为s3的前i + j -1 时,
若s2(j)等于s3(i+j)时,matched[i][j] 为true.
#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>
using namespace std;
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
if(s1.size() + s2.size() != s3.size())
return false;
if(s3.size() == 0)
return true;
bool **matched = new bool*[s1.size() + 1];
for(int i = 0; i <= s1.size(); i++) {
matched[i] = new bool[s2.size() + 1];
memset(matched[i], 0, sizeof(bool) * (s2.size() + 1));
}
for(int i = 0; i < s1.size(); i++) {
if(s1[i] == s3[i])
matched[i + 1][0] = true;
else
break;
}
for(int i = 0; i < s2.size(); i++) {
if(s2[i] == s3[i])
matched[0][i + 1] = true;
else
break;
}
for(int i = 1; i <= s1.size(); i++) {
for(int j = 1; j <= s2.size(); j++) {
if(s2[j - 1] == s3[i + j -1]) {
if(matched[i][j - 1])
matched[i][j] = true;
}
if(s1[i - 1] == s3[j + i - 1]) {
if(matched[i - 1][j])
matched[i][j] = true;
}
}
}
bool result = matched[s1.size()][s2.size()];
for(int i = 0; i <= s1.size(); i++) {
delete[] matched[i];
}
delete[] matched;
return result;
}
};