题目:
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的前i个字符,s2前j个字符,可以组成s3前i+j个字符。最终返回dp[len1][len2]
递推公式:如果dp[i-1][j]为true,s1第i个字符和s3第i+j个字符一样,则dp[i][j]为true
或者 如果dp[i][j-1]为true,s2第j个字符和s3第i+j个字符一样,则dp[i][j]为true
代码:
public boolean isInterleave(String s1, String s2, String s3) {
int len1 = s1.length();
int len2 = s2.length();
int len3 = s3.length();
if(len1+len2!=len3)
return false;
//dp的含义:dp[i][j]表示,s1的前i个字符,s2前j个字符,可以组成s3前i+j个字符
boolean dp[][] = new boolean [len1+1][len2+1];
//init
dp[0][0]=true;
for(int i=1;i<=len1;i++)
dp[i][0]=s3.startsWith(s1.substring(0, i));
for(int j=1;j<=len2;j++)
dp[0][j]=s3.startsWith(s2.substring(0, j));
for(int i=1;i<=len1;i++){
for(int j=1;j<=len2;j++){
if(dp[i][j-1]&&(s2.charAt(j-1)==s3.charAt(i+j-1))){
dp[i][j]=true;
continue;
}
if(dp[i-1][j]&&(s1.charAt(i-1)==s3.charAt(i+j-1))){
dp[i][j]=true;
continue;
}
dp[i][j]=false;
}
}
return dp[len1][len2];
}
优化:在init时候,可以不用startsWith,也采用dp的思维,见代码
public boolean isInterleave(String s1, String s2, String s3) {
int len1 = s1.length();
int len2 = s2.length();
int len3 = s3.length();
if(len1+len2!=len3)
return false;
//dp的含义:dp[i][j]表示,s1的前i个字符,s2前j个字符,可以组成s3前i+j个字符
boolean dp[][] = new boolean [len1+1][len2+1];
//init
dp[0][0]=true;
for(int i=1;i<=len1;i++)
dp[i][0]=dp[i-1][0]&&(s1.charAt(i-1)==s3.charAt(i-1));
for(int j=1;j<=len2;j++)
dp[0][j]=dp[0][j-1]&&(s2.charAt(j-1)==s3.charAt(j-1));
for(int i=1;i<=len1;i++){
for(int j=1;j<=len2;j++){
if(dp[i][j-1]&&(s2.charAt(j-1)==s3.charAt(i+j-1))){
dp[i][j]=true;
continue;
}
if(dp[i-1][j]&&(s1.charAt(i-1)==s3.charAt(i+j-1))){
dp[i][j]=true;
continue;
}
dp[i][j]=false;
}
}
return dp[len1][len2];
}