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问题。
用数组dp[i][j]记录取s1[1,i]和s2[1,j]交叉拼接出s3[1,i+j]。然后我们可以从此时s3最后一个字符的来源分出两个子问题。
于是有递推式如下:
dp[i][j] = (dp[i-1][j] && s1[i-1] == s3[i+j-1]) || (dp[i][j-1] && s2[j-1] == s3[i+j-1])
dp的初始化也十分简单,考虑s1为空(dp第一行),只用s2匹配s3;或者,s2为空(dp第一列),只用s1匹配s3的情形即可。
代码如下:
1 public class Solution { 2 public boolean isInterleave(String s1, String s2, String s3) { 3 int len1 = s1.length(); 4 int len2 = s2.length(); 5 int len3 = s3.length(); 6 if(len3 != len1 + len2) 7 return false; 8 9 boolean[][] dp = new boolean[len1+1][len2+1]; 10 dp[0][0] = true; 11 12 for(int i = 1;i<=len2;i++){ 13 if(s2.charAt(i-1) == s3.charAt(i-1)) 14 dp[0][i]= true; 15 else { 16 break; 17 } 18 } 19 20 for(int i = 1;i<=len1;i++){ 21 if(s1.charAt(i-1) == s3.charAt(i-1)) 22 dp[i][0]= true; 23 else 24 break; 25 } 26 27 for(int i = 1;i<= len1;i++){ 28 char ch1 = s1.charAt(i-1); 29 for(int j = 1;j<=len2;j++){ 30 int k = i+j; 31 char ch2 = s2.charAt(j-1); 32 char ch3 = s3.charAt(k-1); 33 if(ch1 == ch3) 34 dp[i][j] = dp[i][j] | dp[i-1][j]; 35 if(ch2 == ch3) 36 dp[i][j]= dp[i][j] | dp[i][j-1]; 37 } 38 } 39 40 return dp[len1][len2]; 41 } 42 }
【leetcode刷题笔记】Interleaving String,布布扣,bubuko.com
【leetcode刷题笔记】Interleaving String
原文:http://www.cnblogs.com/sunshineatnoon/p/3869805.html