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.
[解题思路]
DP
Let F(i, j) denote if s1 of length i and s2 of length j could form s3 of lenght i+j, then we have four cases:
(1) F(i, j) = F(i-1, j) if s1[i-1] == s3[i+j-1] && s2[j-1] != s3[i +j -1]
(2) F(i, j) = F(i, j-1) if s1[i-1] != s3[i+j-1] && s2[j-1] == s3[i +j -1]
(3) F(i, j) = F(i-1, j) || F(i, j-1) if s1[i-1] == s3[i+j-1] && s2[j-1] == s3[i +j -1]
(4) F(i, j) = false if s1[i-1] != s3[i+j-1] && s2[j-1] != s3[i +j -1]
1 public class Solution { 2 public boolean isInterleave(String s1, String s2, String s3) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 int len1 = s1.length(), len2 = s2.length(), len3 = s3.length(); 6 if(len3 != len1 + len2){ 7 return false; 8 } 9 10 boolean[][] match = new boolean[len1 + 1][len2 + 1]; 11 match[0][0] = true; 12 13 // j == 0 14 int i = 1; 15 while(i <= len1 && s1.charAt(i-1) == s3.charAt(i-1)){ 16 match[i][0] = true; 17 i++; 18 } 19 20 // i == 0 21 int j = 1; 22 while(j <= len2 && s2.charAt(j-1) == s3.charAt(j-1)){ 23 match[0][j] = true; 24 j++; 25 } 26 27 for(int m = 1; m <= len1; m++){ 28 for(int n = 1; n <= len2; n++){ 29 char c = s3.charAt(m + n - 1); 30 if(c == s1.charAt(m - 1)){ 31 match[m][n] |= match[m-1][n]; 32 } 33 if(c == s2.charAt(n - 1)){ 34 match[m][n] |= match[m][n-1]; 35 } 36 } 37 } 38 return match[len1][len2]; 39 } 40 }
ref:http://fisherlei.blogspot.com/2012/12/leetcode-interleaving-string.html