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最后一个字符的来源分出两个子问题。
- 如果s3最后一个字符来源于s2,那么我们只要考察用s1[1,i]和s2[1,j-1]能否交叉拼接出s3[1,i+j-1]这个子问题。比如s1 = "aa", s2 = "b", s3 = "aab",此时s3最后一个字符"b"来源于s2,那么我们只要考察s1 = "aa" 和 s2 = ""能否交叉拼接出s3 = "aa"即可。
- 如果s3最后一个字符来源于s1,那么同理,我们只要考察用s[1,i-1]和s2[1,j]能否交叉拼接出s3[1,i+j-1]这个子问题。
于是有递推式如下:
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
时间: 2024-12-29 06:50:06