Interleaving String, interleavingstring
GivenS1,S2,S3, Find whetherS3Is formed by the interleavingS1AndS2.
For example,
Given:
S1="aabcc",
S2="dbbca",
WhenS3="aadbbcbcac", Return true.
WhenS3="aadbbbaccc", Return false.
The simplest way of thinking is to do recursion, but this requires recursion at most s3 length layers, which consumes a lot and is prone to timeout errors. A timeout error occurs when performing recursive attempts, recursion is the most intuitive way to solve this problem.
Recursive method does not consider DP, we use path [I] [j] to record s1 to I and s2 to j and s3 [I + J-1] whether the requirements are met, this process is to fill in a two-dimensional array table. First initialize the first row and the first column, then fill in the table to calculate all, and return the value of path [s1.length] [s2.length.
AC code:
public class Solution { public boolean isInterleave(String s1, String s2, String s3) {if(s1.length()+s2.length()!=s3.length()){return false;}int row = s1.length();int col = s2.length();boolean [][]path = new boolean[row+1][col+1];path[0][0] = true;for(int i=1;i<=row;i++){path[i][0] = path[i-1][0] && (s1.charAt(i-1)==s3.charAt(i-1));}for(int i=1;i<=col;i++){path[0][i] = path[0][i-1] && (s2.charAt(i-1) == s3.charAt(i-1));}for(int i=1;i<=row;i++){for(int j=1;j<=col;j++){path[i][j] = (path[i-1][j] && s1.charAt(i-1)==s3.charAt(i+j-1)) ||(path[i][j-1] && s2.charAt(j-1) == s3.charAt(i+j-1));}}return path[row][col];}}