[Leetcode] 97. Interleaving String Java

题目:

Given s1s2s3, 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.

题意及分析:给出字符串s1,s2,s3,判断由s1和s2交叉组合能够得到字符串s3。这道题我一开始想到了用递归,判断每次从s1或者s2加一个点是否能得到s3下一个点,但是最后超时。这道题因为只有s1和s2,所有我们可以看成一个矩阵,看是否能从左上角走到右下角。

当S1到达第i个元素,s2到达第j个元素时:

(1)往右走一步,相当于s2[j-1]匹配s3[i+j-1]

(2)往下走一步,相当于s1[i-1]匹配s3[i+j-1]

这里需要注意的是i==0或j==0时需要单独处理。

用一个二维数组保存是否能到达当前点,最右下角的值便是判断结果。

代码:

class Solution {
    public boolean isInterleave(String s1, String s2, String s3) {   //判断能否有s1和s2按顺序交叉组合成s3
        if(s1.length() + s2.length() != s3.length()) return false;
        boolean[][] path = new boolean[s1.length()+1][s2.length()+1];
        for(int i = 0;i<=s1.length();i++){
            for (int j=0;j<=s2.length();j++){
                if(i==0&&j==0)
                    path[i][j] = true;
                else if(i==0){
                    path[i][j] = path[i][j-1] && (s2.charAt(j-1) == s3.charAt(j-1));
                }else if(j==0){
                    path[i][j] = path[i-1][j] && (s1.charAt(i-1) == s3.charAt(i-1));
                }else{
                    path[i][j] = (path[i-1][j] && (s1.charAt(i-1) == s3.charAt(i+j-1))) || (path[i][j-1] && (s2.charAt(j-1) == s3.charAt(i+j-1)));
                }
            }
        }
        return path[s1.length()][s2.length()];
    }
}
原文地址:https://www.cnblogs.com/271934Liao/p/7967209.html