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.
Using DP, the process is as follows:
S2 |
S1 |
Aadbbcbcac |
0 "" |
1 d |
2 db |
3 DBB |
4 DBBC |
5 DBBCA |
0 "" |
T |
F (D!=a) |
F |
F |
F |
F |
1 A |
T (A==a) |
F (AA) |
F |
F |
F |
F |
2 AA |
T |
T (AAD) |
T (AADB) |
|
|
|
3 AaB |
F (Aab!=aad) |
T (AADB) |
T (AADBB) |
|
|
|
4 AABC |
F |
F (AADBB) |
T (AADBBC) |
|
|
|
5 AABCC |
F |
F (AADBBC) |
|
|
|
|
A dp[i][j] is found to be true only if it is true above or to the left. And the newly added letters need to be the same as the new letters S3, the true state can be continued.
Code:
1 Public BooleanIsinterleave (string s1, String s2, string s3) {2 intl1=s1.length ();3 intL2=s2.length ();4 intl3=s3.length ();5 if(l1+l2!=L3)6 return false;7 Boolean[] DP =New Boolean[L1+1] [L2+1];8 for(inti=0;i<=l1;i++) {9 for(intj=0;j<=l2;j++) {Ten if(I==0 && j==0) Onedp[i][j]=true; A Else if(i==0) -DP[I][J] = dp[i][j-1] && (S2.charat (j-1) ==s3.charat (i+j-1)); - Else if(j==0) theDP[I][J] = Dp[i-1][j] && (S1.charat (i-1) ==s3.charat (i+j-1)); - Else -DP[I][J] = (Dp[i][j-1] && (S2.charat (j-1) ==s3.charat (i+j-1))) | | (Dp[i-1][j] && (S1.charat (i-1) ==s3.charat (i+j-1))); - } + } - returnDP[L1][L2]; +}
Simplify to one-dimensional arrays:
1 Public BooleanIsinterleave (string s1, String s2, string s3) {2 intL1 =s1.length ();3 intL2 =s2.length ();4 intL3 =s3.length ();5 if(L3!= (l1+L2))6 return false;7 Boolean[] DP =New Boolean[L2+1];8Dp[0] =true;9 for(inti=1;i<dp.length;i++)Ten { OneDp[i] = dp[i-1] && (S2.charat (i-1) ==s3.charat (i-1)); A } - for(inti=1;i<=l1;i++) - { the for(intj=0;j<dp.length;j++) - { - if(j==0) -DP[J] = Dp[j] && (S1.charat (i-1) ==s3.charat (i-1)); + Else -DP[J] = (Dp[j] && (S1.charat (i-1) ==s3.charat (i+j-1))) | | (Dp[j-1] && (S2.charat (j-1) ==s3.charat (i+j-1))); + } A } at - returnDP[L2]; -}
[Leetcode] [JAVA] Interleaving String