(Version 0.0)
Interleaving string This problem is a typical DP topic, the idea is the most basic use of the previous subproblem (substring) solution plus the current char judgment to solve the current problem of the typical sequence DP problem. The general sub-problems we want to consider are: Take s1.substring (i) and S2.substring (j), can interleave into s3.substring (i + j). If S1.substring (i) and s2.substring (j) want to interleave into s3.substring (i + j), then s1.substring (i) and S2.substring (j) There must be at least one and s3.substring (i + j) having the same last char, so an easy state transition relationship: if S1.charat (i-1) and S3.charat (i + j-1) match, then s1.substring (i-1) and S2.substring (j) must be resolved together s3.substring (i + j-1), i.e. dp[i-1][j] && s1.charat (i-1) = = S3.charat (i + j-1); or if you go to s2.ch Arat (j-1) and S3.charat (i + j-1) match, then s1.substring (i) and s2.substring (j-1) must be resolved together s3.substring (i + j-1), i.e. dp[i][j-1] && Amp S2.charat (j-1) = = S3.charat (i + j-1). The code is as follows:
1 Public classSolution {2 Public BooleanIsinterleave (string s1, String s2, string s3) {3 if(S1.length () + s2.length ()! =s3.length ()) {4 return false;5 }6 Boolean[] DP =New Boolean[S1.length () + 1] [S2.length () + 1];7Dp[0][0] =true;8 for(inti = 1; I <= s2.length (); i++) {9 if(Dp[0][i-1] && s3.charat (i-1) = = S2.charat (i-1)) {TenDp[0][i] =true; One}Else { A Break; - } - } the for(inti = 1; I <= s1.length (); i++) { - if(Dp[i-1][0] && s3.charat (i-1) = = S1.charat (i-1)) { -Dp[i][0] =true; -}Else { + Break; - } + } A for(inti = 1; I <= s1.length (); i++) { at for(intj = 1; J <= S2.length (); J + +) { - Charc = S3.charat (i + j-1); -DP[I][J] = dp[i][j-1] && s2.charat (j-1) = = C | | DP[I-1][J] && s1.charat (i-1) = =C; - } - } - returndp[s1.length ()][s2.length ()]; in } -}
In general, as long as the master clrs or other textbooks above the sequence DP example, you will find this problem in fact, you can apply the typical DP mode.
[Leetcode] Interleaving String