首页 > 代码库 > Leetcode-Interleaving String
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.
Analysis:
Initially, we consider the state d[k,i,j] as whether the first k chars in s3 is the interleaving string of the first i chars of s1 and the first j chars of s2. We then have the formula:
d[k,i,j] = d[k-1][i-1][j] && s3[k]==s1[i] || d[k-1][i][j-1] && s3[k]==s2[j].
We then find that since a state d[k,i,j] has meaning only when k==(i+j), we actaully can reduce the number of states. We further use the state d[i,j] to present whether the s1[0-(i-1)] and s2[0-(j-1)] can interleave to s3[0-(i+j-1)]. we have formula:
d[i][j] = d[i-1][j] && s3[i+j-1]==s1[i-1] || d[i][j-1] && s3[i+j-1]==s2[j-1].
Solution:
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 6 //NOTE: need to consider this boundary case! 7 if (s3.length()!=len1+len2) return false; 8 9 boolean[][] d = new boolean[len1+1][len2+1];10 d[0][0]=true;11 for (int i=1;i<=len2;i++)12 if (d[0][i-1] && s2.charAt(i-1)==s3.charAt(i-1))13 d[0][i]=true;14 else d[0][i]=false;15 16 for (int i=1;i<=len1;i++)17 if (d[i-1][0] && s1.charAt(i-1)==s3.charAt(i-1))18 d[i][0]=true;19 else d[i][0]=false;20 21 for (int i=1;i<=len1;i++)22 for (int j=1;j<=len2;j++)23 if (d[i-1][j] && s1.charAt(i-1)==s3.charAt(i+j-1))24 d[i][j]=true;25 else if (d[i][j-1] && s2.charAt(j-1)==s3.charAt(i+j-1))26 d[i][j]=true;27 else d[i][j]=false;28 29 30 return d[len1][len2]; 31 }32 }
Leetcode-Interleaving String