题目
两个字符串可以拼接成一个否?
思考
1 可以用dp来做。但是会TLE
2 数组记录法来做。但要注意坐标,非常容易出错。
代码
public class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
if(s3 == null || s3.length()==0){
return true;
}
char ch = s3.charAt(0);
if(s1.length()>0 && ch == s1.charAt(0)){
if(isInterleave(s1.substring(1),s2,s3.substring(1))){
return true;
}
}
if(s2.length()>0 && ch == s2.charAt(0)){
if(isInterleave(s1,s2.substring(1),s3.substring(1))){
return true;
}
}
return false;
}
}
public class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
if(s3 == null || s1==null || s2 == null){
return false;
}
int l1 = s1.length();
int l2 = s2.length();
int l3 = s3.length();
if(l1+l2!=l3){
return false;
}
boolean[][] record = new boolean[l1+1][l2+1];
record[0][0] = true;
for(int i=1;i<=l1;i++){
if(!record[i-1][0] || s1.charAt(i-1)!= s3.charAt(i-1)){
break;
}
record[i][0] = true;
}
for(int j=1;j<=l2;j++){
if(!record[0][j-1] || s2.charAt(j-1)!= s3.charAt(j-1)){
break;
}
record[0][j] = true;
}
for(int i = 1;i<=l1;i++){
for(int j = 1;j<=l2;j++){
if(record[i-1][j] && s1.charAt(i-1)==s3.charAt(i+j-1)){
record[i][j]=true;
}
if(record[i][j-1] && s2.charAt(j-1)==s3.charAt(i+j-1)){
record[i][j]=true;
}
}
}
return record[l1][l2];
}
}