LeetCode Interleaving String
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.
Question: Can the s1 and s2 strings be combined into S3.
Idea: DP is done. dp [I + 1] [j + 1] indicates s1 [0... i] and s2 [0... j] whether it can be combined into s3 [I + j + 1]. When dp [I] [j + 1] is true, if s1 [I + 1] = s3 [I + j + 1], dp [I + 1] [j + 1] will meet the requirements, the same is true for dp [I + 1] [j.
public class Solution { public boolean isInterleave(String s1, String s2, String s3) { int m = s1.length(), n = s2.length(); if (m + n != s3.length()) return false; boolean dp[][] = new boolean[m+1][n+1]; dp[0][0] = true; for (int i = 0; i < n; i++) dp[0][i+1] = dp[0][i] && (s2.charAt(i) == s3.charAt(i)); for (int i = 0; i < m; i++) dp[i+1][0] = dp[i][0] && (s1.charAt(i) == s3.charAt(i)); for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) dp[i+1][j+1] = (dp[i][j+1] && (s1.charAt(i) == s3.charAt(i+j+1)) || (dp[i+1][j] && (s2.charAt(j) == s3.charAt(i+j+1)))); return dp[m][n]; }}