[Leetcode]Interleaving String

来源:互联网 发布:淘宝400电话 编辑:程序博客网 时间:2024/06/07 09:31

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.


用二维dp来做,建立一个二维布尔数组match[l1][l2]用来记录状态。match[i][j] = true表示s1中的[0——i-1],长为i的子串和s2中[0——j-1] ,长位j的子串能够表示出s3中长为i + j的子串。如此一来问题就可以分解为bottom-up类型的二维dp了。


public boolean isInterleave(String s1, String s2, String s3) {        if (s1.length() + s2.length() != s3.length())            return false;                boolean[][] match = 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)                    match[i][j] = true;                else if (i == 0) {                    if (match[i][j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1))                        //i=0的情况下,s3只由s2决定                        match[i][j] = true;                    else                        match[i][j] = false;                } else if (j == 0) {                    if (match[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1))                        //i=0的情况下,s3只由s1决定                        match[i][j] = true;                    else                         match[i][j] = false;                } else {                    if (match[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1) ||                        match[i][j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1))                        match[i][j] = true;                    else                         match[i][j] = false;                }            }        }        return match[s1.length()][s2.length()];    }




0 0
原创粉丝点击