97. Interleaving String

来源:互联网 发布:cst仿真软件如何 编辑:程序博客网 时间:2024/06/07 21:12

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(object):    def isInterleave(self, s1, s2, s3):        """        :type s1: str        :type s2: str        :type s3: str        :rtype: bool        """        if len(s1) + len(s2) != len(s3):            return False        m = [[False for _ in xrange(len(s1) + 1)] for _ in xrange(len(s2) + 1)]        m[0][0] = True        for i in xrange(1, len(s1)+1):            m[0][i] = m[0][i - 1] and (s1[i - 1] == s3[i - 1])        for i in xrange(1, len(s2)+1):            m[i][0] = m[i - 1][0] and (s2[i - 1] == s3[i - 1])        for i in xrange(1, len(s2)+1):            for j in xrange(1, len(s1)+1):                m[i][j] = (m[i][j - 1] and s1[j - 1] == s3[i+j-1]) or (m[i-1][j] and s2[i - 1] == s3[i+j-1])        return m[len(s2)][len(s1)]        


原创粉丝点击