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.
解题思路:
来自http://blog.csdn.net/u011095253/article/details/9248073
但是递归解法会超时,可以参考下;
下面DP解法也不是最优的,后续会修改。
public class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
if(s1.length() + s2.length() != s3.length())
return false;
return assist(s1,0,s2,0,s3,0);
}
public boolean assist(String s1,int t1,String s2,int t2,String s3,int t3){
if(t3 == s3.length())
return true;
if(t1 == s1.length()) return s2.substring(t2).equals(s3.substring(t3));
if(t2 == s2.length()) return s1.substring(t1).equals(s3.substring(t3));
if(s1.charAt(t1) == s3.charAt(t3) && s2.charAt(t2) == s3.charAt(t3))
return assist(s1,t1+1,s2,t2,s3,t3+1) || assist(s1,t1,s2,t2+1,s3,t3+1);
if(s1.charAt(t1) == s3.charAt(t3))
return assist(s1,t1+1,s2,t2,s3,t3+1);
if(s2.charAt(t2) == s3.charAt(t3))
return assist(s1,t1,s2,t2+1,s3,t3+1);
return false;
}
}
DP解法:
public class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
if(s1.length() + s2.length() != s3.length())
return false;
boolean dp[][] = new boolean[s1.length()+1][s2.length()+1];
dp[0][0] = true;
for(int i = 1; i <= s1.length(); i++){
if(s1.charAt(i-1) == s3.charAt(i-1) && dp[i-1][0]){
dp[i][0] = true;
}
}
for(int j = 1; j <= s2.length(); j++){
if(s2.charAt(j-1) == s3.charAt(j-1) && dp[0][j-1]){
dp[0][j] = true;
}
}
for(int i = 1; i <= s1.length(); i++)
for(int j = 1; j <= s2.length(); j++){
if(s1.charAt(i-1) == s3.charAt(i+j-1) && dp[i-1][j])
dp[i][j] = true;
if(s2.charAt(j-1) == s3.charAt(i+j-1) && dp[i][j-1])
dp[i][j] = true;
}
return dp[s1.length()][s2.length()];
}
}