97. Interleaving String

Description

Given s1, s2, s3, 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.

Solution

DP, time O(m * n), space O(m * n)

跟Edit distance相同的思路。
dp[i][j]代表s1.substring(0, i)和s2.substring(0, j)是否能匹配s3.substring(0, i + j)。注意需要处理i = 0和j = 0的情况哦。

class Solution {
    public boolean isInterleave(String s1, String s2, String s3) {
        if (s1 == null || s2 == null || s3 == null 
            || s1.length() + s2.length() != s3.length()) {
            return false;
        }
        
        int m = s1.length();
        int n = s2.length();
        boolean[][] dp = new boolean[m + 1][n + 1];
        
        for (int i = 0; i <= m; ++i) {
            for (int j = 0; j <= n; ++j) {
                if (i == 0 && j == 0) {
                    dp[i][j] = true;
                    continue;
                }
                
                dp[i][j] = i > 0 && s1.charAt(i - 1) == s3.charAt(i + j - 1) && dp[i - 1][j];
                dp[i][j] |= j > 0 && s2.charAt(j - 1) == s3.charAt(i + j - 1) && dp[i][j - 1];
            }
        }
        
        return dp[m][n];
    }
}

你可能感兴趣的:(97. Interleaving String)