题目
leetcode 97
给定三个字符串 s1, s2, s3, 验证 s3 是否是由 s1 和 s2 交错组成的。
示例 1:
输入: s1 = “aabcc”, s2 = “dbbca”, s3 = “aadbbcbcac”
输出: true
示例 2:
输入: s1 = “aabcc”, s2 = “dbbca”, s3 = “aadbbbaccc”
输出: false
代码
动态规划,挺难想到的,看了题解。
bool isInterleave(char * s1, char * s2, char * s3){
int len1 = strlen(s1), len2 = strlen(s2), len3 = strlen(s3);
if (len1 + len2 != len3) return false;
int dp[len1 + 1][len2 + 1];
dp[0][0] = 1;
for (int i = 0; i <= len1; i++) {
for (int j = 0; j <= len2; j++) {
if (i == 0 && j == 0) continue;
if (i == 0) {
if (dp[0][j - 1] && s2[j - 1] == s3[j - 1]) dp[0][j] = 1;
else dp[0][j] = 0;
} else if (j == 0) {
if (dp[i - 1][0] && s1[i - 1] == s3[i - 1]) dp[i][0] = 1;
else dp[i][0] = 0;
} else {
if (dp[i - 1][j] && s1[i - 1] == s3[i + j - 1]) dp[i][j] = 1;
else if (dp[i][j - 1] && s2[j - 1] == s3[i + j - 1]) dp[i][j] = 1;
else dp[i][j] = 0;
}
}
}
return dp[len1][len2];
}