交错字符串
题目:
给定三个字符串 s1、s2、s3,请你帮忙验证 s3 是否是由 s1 和 s2 交错 组成的。
两个字符串 s 和 t 交错 的定义与过程如下,其中每个字符串都会被分割成若干 非空 子字符串:
s = s1 + s2 + ... + sn
t = t1 + t2 + ... + tm
|n - m| <= 1
交错 是 s1 + t1 + s2 + t2 + s3 + t3 + ... 或者 t1 + s1 + t2 + s2 + t3 + s3 + ...
提示:a + b 意味着字符串 a 和 b 连接。
输入:s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
输出:true
示例 2:
输入:s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
输出:false
示例 3:
输入:s1 = "", s2 = "", s3 = ""
输出:true
解题思路:首先从s3的最后一个字符开始思考,最后一个字符是来自s1[0..s1.length - 1] || s2[0..s2.length - 1],如果该字符来自s1那么s3的倒数第二个字符就来自s1[0..s1.length - 2] || s2[0..s2.length - 1],此时再来推断倒数第二个字符来自s1还是s2以此类推
class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
int len1 = s1.length(), len2 = s2.length(), len3 = s3.length();
char[] ch1 = s1.toCharArray(), ch2 = s2.toCharArray(), ch3 = s3.toCharArray();
if(len1 + len2 != len3) {
return false;
}
// 数组定义:dp[i][j]表示s1[0..i - 1]和s2[0..j - 1]能否拼出s3[0..i + j - 1]
boolean dp[][] = new boolean[len1 + 1][len2 + 1];
// 初始化 s1 s2为空串可以拼出s3为空串
dp[0][0] = true;
/**
状态方程 dp[i][j] = (dp[i - 1][j] && ch1[i - 1] == ch3[i + j - 1]) ||
(dp[i][j - 1] && ch2[j - 1] == ch3[i + j - 1])
**/
for(int i = 0; i <= len1; i++) {
for(int j = 0; j <= len2; j++) {
if(i > 0 && ch1[i - 1] == ch3[i + j - 1]) {
dp[i][j] |= dp[i - 1][j];
}
if(j > 0 && ch2[j - 1] == ch3[i + j - 1]) {
dp[i][j] |= dp[i][j - 1];
}
}
}
return dp[len1][len2];
}
}