美文网首页
2020-10-28

2020-10-28

作者: 为什么我这么笨 | 来源:发表于2020-10-28 03:27 被阅读0次

    Description:

    Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.

    Example 1:

    Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"

    Output: true

    Example 2:

    Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"

    Output: false

    Solutions: 递归

    class Solution:

        def isInterleave(self, s1: str, s2: str, s3: str) -> bool:

            if len(s1)+len(s2) != len(s3): # corner cases

                return False

           

            dp = [[None for j in range(len(s1)+1)] for i in range(len(s2)+1)]

            dp[-1][-1] = True # The Destination should be True

           

            def search(cnt,row,col):

                if dp[row][col] != None:

                    return dp[row][col]

               

                if row < len(s2) and s2[row] == s3[cnt] and search(cnt+1,row+1,col): # move downward

                    dp[row][col] = True

                    return True

                if col < len(s1) and s1[col] == s3[cnt] and search(cnt+1,row,col+1): # move right

                    dp[row][col] = True

                    return True

                dp[row][col] = False # fail to find a path

                return False

           

            return search(0,0,0)

            # print("\n-------------------------")

            # for d in dp:

            #    print(d)

    Runtime: 36 ms, faster than 88.84% of Python3 online submissions for Interleaving String.

    Memory Usage: 13.6 MB, less than 5.07% of Python3 online submissions for Interleaving String.

    相关文章

      网友评论

          本文标题:2020-10-28

          本文链接:https://www.haomeiwen.com/subject/tuafvktx.html