dp[i][j]意思是s1前i个字符插入了s2的前j个字符。
public class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
if(s3.length() != s1.length() + s2.length())
return false;
boolean[][]dp = new boolean[s1.length()+1][s2.length()+1];
for(int i=0; i<s1.length()+1; i++)
for(int j=0; j< s2.length()+1; j++){
if(i==0&&j==0){
dp[i][j]=true;
continue;
}
if(i==0){
if(s3.charAt(i+j-1)==s2.charAt(j-1)&&dp[i][j-1])
dp[i][j] = true;
}else if(j==0){
if(s3.charAt(i+j-1)==s1.charAt(i-1)&&dp[i-1][j])
dp[i][j] = true;
}else{
if((s3.charAt(i+j-1)==s1.charAt(i-1)&&dp[i-1][j])||(s3.charAt(i+j-1)==s2.charAt(j-1)&&dp[i][j-1]))
dp[i][j] = true;
}
}
return dp[s1.length()][s2.length()];
}
}
本文介绍了一种用于判断两个字符串是否能交错组成第三个字符串的算法。通过动态规划的方法,该算法构建了一个二维布尔数组来记录子问题的解决方案。文章详细解释了算法的实现过程及其核心逻辑。
687

被折叠的 条评论
为什么被折叠?



