097 Interleaving String

097 Interleaving String

这道题也是纯dp了

class Solution:
    # @param {string} s1
    # @param {string} s2
    # @param {string} s3
    # @return {boolean}
    def isInterleave(self, s1, s2, s3):
        m = len(s1)
        n = len(s2)
        if m + n != len(s3):
            return False
        dp = [[False] * (n+1) for i in range(0, m+1)]
        dp[0][0] = True
        for j in range(1, n+1):
            dp[0][j] = (s2[:j] == s3[:j])
        for i in range(1, m+1):
            dp[i][0] = (s1[:i] == s3[:i])
        for i in range(1, m + 1):
            for j in range(1, n + 1):
                a1, a2, a3 = s1[i-1], s2[j-1], s3[i+j-1]
                if a3 != a1 and a3 != a2:
                    dp[i][j] = False
                elif a3 == a1 and a3 == a2:
                    dp[i][j] = (dp[i-1][j] or dp[i][j-1])
                elif a3 == a1:
                    dp[i][j] = dp[i-1][j]
                else:
                    dp[i][j] = dp[i][j-1]
        return dp[m][n]

 

posted @ 2015-07-30 00:23  dapanshe  阅读(110)  评论(0编辑  收藏  举报