97. 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.

 

 

 

 

class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        if len(s1) + len(s2) != len(s3):
            return False
        m=len(s1)
        n=len(s2)
        dp = [[0]*(n+1) for _ in range(m+1)]
        dp[0][0] = 1
        for i in range(1,m+1):
            dp[i][0] = (dp[i-1][0] and s1[i-1] == s3[i+0-1]) 
        for j in range(1,n+1):
            dp[0][j] = (dp[0][j-1] and s2[j-1] == s3[0+j-1])
        for i in range(1,m+1):
            for j in range(1,n+1):
                dp[i][j] = (dp[i-1][j] and s1[i-1] == s3[i+j-1]) or (dp[i][j-1] and s2[j-1] == s3[i+j-1])
        return dp[m][n] == 1

 

动态规划 

 1 public class Solution {
 2     public boolean isInterleave(String s1, String s2, String s3) {
 3         if (s3.length() != s1.length() + s2.length()) {
 4             return false;
 5         }
 6         boolean dp[][] = new boolean[s1.length() + 1][s2.length() + 1];
 7         for (int i = 0; i <= s1.length(); i++) {
 8             for (int j = 0; j <= s2.length(); j++) {
 9                 if (i == 0 && j == 0) {
10                     dp[i][j] = true;
11                 } else if (i == 0) {
12                     dp[i][j] = dp[i][j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1);
13                 } else if (j == 0) {
14                     dp[i][j] = dp[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1);
15                 } else {
16                     dp[i][j] = (dp[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1)) || (dp[i][j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1));
17                 }
18             }
19         }
20         return dp[s1.length()][s2.length()];
21     }
22 }

 

posted @ 2018-03-09 14:48  乐乐章  阅读(389)  评论(0编辑  收藏  举报