# 97-字符串交织

Description

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.

class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
int len1 = s1.length(), len2 = s2.length(), len3 = s3.length();
if(len1 + len2 != len3) return false;

int[][] dp = new int[len1 + 1][len2 + 1];

return dfs(s1, s2, s3, 0, 0, dp);
}
public boolean dfs(String s1, String s2, String s3, int index1, int index2, int[][] dp){
if(index1 + index2 == s3.length())  return true;

if(dp[index1][index2] != 0) return dp[index1][index2] == 1;

boolean left = false;
if(index1 < s1.length() && s1.charAt(index1) == s3.charAt(index1 + index2)) left = dfs(s1, s2, s3, index1 + 1, index2, dp);
boolean right = false;
if(index2 < s2.length() && s2.charAt(index2) == s3.charAt(index1 + index2)) right = dfs(s1, s2, s3, index1, index2 + 1, dp);
dp[index1][index2] = left || right ? 1 : 2;

return left || right;
}
}

class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
int len1 = s1.length(), len2 = s2.length(), len3 = s3.length();
if(len1 + len2 != len3) return false;

boolean[][] dp = new boolean[len1 + 1][len2 + 1];

for(int i = 0;i <= len1;i++){
for(int j = 0;j <= len2;j++){
if(i == 0 && j == 0){
dp[i][j] = true;
}else if(i == 0){
dp[i][j] = s2.charAt(j - 1) == s3.charAt(i + j - 1) && dp[i][j - 1];
}else if(j == 0){
dp[i][j] = s1.charAt(i - 1) == s3.charAt(i + j - 1) && dp[i - 1][j];
}else{
dp[i][j] = (s1.charAt(i - 1) == s3.charAt(i + j - 1) && dp[i - 1][j]) || (s2.charAt(j - 1) == s3.charAt(i + j - 1) && dp[i][j - 1]);
}
}
}

return dp[len1][len2];
}
}

class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
int len1 = s1.length(), len2 = s2.length(), len3 = s3.length();
if(len1 + len2 != len3) return false;

boolean[] dp = new boolean[len2 + 1];

for(int i = 0;i <= len1;i++){
for(int j = 0;j <= len2;j++){
if(i == 0 && j == 0){
dp[j] = true;
}else if(i == 0){
dp[j] = s2.charAt(j - 1) == s3.charAt(i + j - 1) && dp[j - 1];
}else if(j == 0){
dp[j] = s1.charAt(i - 1) == s3.charAt(i + j - 1) && dp[j];
}else{
dp[j] = (s1.charAt(i - 1) == s3.charAt(i + j - 1) && dp[j]) || (s2.charAt(j - 1) == s3.charAt(i + j - 1) && dp[j - 1]);
}
}
}

return dp[len2];
}
}