LeetCode-Interleaving String

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.


又是一个关于字符串的动态规划题,Distinct Subsequences、Edit Distance都差不多,肯定回溯法是可以解出来的,但是肯定时间复杂度比较高。这时候想起来动态规划算法。分析基本跟上述两个问题的方式是一样的。

还是看住最后一个字符s1[j], s2[i]与s3[i+j-1]之间的关系,代码见下:

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



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