LeetCode刷题笔录Interleaving String

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.


这题的第一反应就是动态规划,转移方程并不难想,主要是对于string长度和下标的关系要想清楚。

dp[i][j]表示用s1的前i个字符和s2的前j个字符能否interleave s3的前i+j个字符。s1的前i个字符是0到i-1;s2前j个字符是从0到j-1;s3前i+j个字符是从0到i+j-1。

dp[i][j]=true iff (dp[i-1][j]=true and s1[i-1]==s3[i+j-1], or dp[i][j-1]=true and s2[j-1]==s3[i+j-1])

base case稍微难想一点,i和j分别为0时,用s1或s2去匹配s3.

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];
        dp[0][0] = true;
        
        for(int i = 0; i < s1.length(); i++){
            if(s1.charAt(i) == s3.charAt(i))
                dp[i + 1][0] = true;
        }
        for(int j = 0; j < s2.length(); j++){
            if(s2.charAt(j) == s3.charAt(j))
                dp[0][j + 1] = true;
        }
        
        for(int i = 1; i <= s1.length(); i++){
            for(int j = 1; j <= s2.length(); j++){
                int c3 = s3.charAt(i + j - 1);
                if((dp[i - 1][j] && s1.charAt(i - 1) == c3) || (dp[i][j - 1] && s2.charAt(j - 1) == c3))
                    dp[i][j] = true;
            }
        }
        return dp[s1.length()][s2.length()];
    }
}


你可能感兴趣的:(动态规划,LeetCode,string,leetcode,string,动态规划)