判断一个字符串是否是有其他两个字符串交错构成的(Interleaving String)

举个例子:
s1 = “aabcc”,
s2 = “dbbca”,

如果 s3 = “aadbbcbcac”, return true.
如果 s3 = “aadbbbaccc”, return false.

1、动态规划

  public  boolean isInterleave(String s1,String s2,String s3){
        int s1len=s1.length(),s2len=s2.length(),s3len=s3.length();
        if(s1len+s2len!=s3len)return false;
        boolean val[][]=new boolean[s1len+1][s2len+1];
        val[0][0]=true;
        for(int i=1;i<=s1len;i++){
            val[i][0]=val[i-1][0]&&s1.charAt(i-1)==s3.charAt(i-1);
        }
        for(int i=1;i<=s2len;i++){
            val[0][i]=val[0][i-1]&&s2.charAt(i-1)==s3.charAt(i-1);
        }
        for(int i=1;i<=s1len;i++){

            for(int j=1;j<=s2len;j++){
                    val[i][j]=(val[i][j-1]&&s2.charAt(j-1)==s3.charAt(i+j-1))||
                            (val[i-1][j]&&s1.charAt(i-1)==s3.charAt(i+j-1));
            }
        }

        return val[s1len][s2len];
    }

2、递归

public boolean isInterleave(String s1, String s2, String s3) {
        if (s1.length() + s2.length() != s3.length()) return false;
       HashSet<Integer> cache = new HashSet<Integer>();
        return isInterleave0(s1, s2, s3, 0, 0,cache);
    }

    public  boolean isInterleave0(String s1, String s2, String s3, int p1, int p2,HashSet<Integer> cache) {
        if (p1 + p2 == s3.length())
            return true;
       if (cache.contains(p1 * s3.length() + p2))
            return false;
        // no need to store actual result.
        // if we found the path, we have already terminated.
        cache.add(p1 * s3.length() + p2);
        boolean match1 = p1 < s1.length() && s3.charAt(p1 + p2) == s1.charAt(p1);
        boolean match2 = p2 < s2.length() && s3.charAt(p1 + p2) == s2.charAt(p2);
        if (match1 && match2)
            return isInterleave0(s1, s2, s3, p1 + 1, p2,cache) ||
                   isInterleave0(s1, s2, s3, p1, p2 + 1,cache);
        else if (match1)
            return isInterleave0(s1, s2, s3, p1 + 1, p2,cache);
        else if (match2)
            return isInterleave0(s1, s2, s3, p1, p2 + 1,cache);
        else
            return false;
    }

你可能感兴趣的:(算法)