Given s1, S2, S3, find whether S3 are 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.
Public classSolution { Public BooleanIsinterleave (string s1, String s2, string s3) {//Dynamic programming idea, constructs a two-dimensional array, Dp[i][j] Indicates whether the S1 of the first I bit and S2 of the first J-bit meet the requirements//The state transition equation is dp[i][j]= (Dp[i-1][j]&&s1.charat (i-1) ==s3.charat (i+j-1)) | | (Dp[i][j-1]&&s2.charat (j-1) ==s3.charat (i+j-1)); //attention to the subscript problem, the size of DP is [len1+1][len2+1], Dp[0][j] represents 0 S1 characters and J S2 characters to meet the requirements of a string intlen1=s1.length (); intLen2=s2.length (); intlen3=s3.length (); if(LEN1+LEN2!=LEN3)return false; Booleandp[][]=New Boolean[Len1+1] [Len2+1]; dp[0][0]=true; for(inti=1;i<=len1;i++) {dp[i][0]=dp[i-1][0]&&s1.charat (i-1) ==s3.charat (i-1); } for(intj=1;j<=len2;j++) {dp[0][j]=dp[0][j-1]&&s2.charat (j-1) ==s3.charat (j-1); } for(inti=1;i<=len1;i++){ for(intj=1;j<=len2;j++) {Dp[i][j]= (Dp[i-1][j]&&s1.charat (i-1) ==s3.charat (i+j-1)) | | (Dp[i][j-1]&&s2.charat (j-1) ==s3.charat (i+j-1)); } } returnDp[len1][len2]; }}
[Leedcode 97] Interleaving String