Skip to content

Latest commit

 

History

History
144 lines (80 loc) · 2.64 KB

0097._Interleaving_String.md

File metadata and controls

144 lines (80 loc) · 2.64 KB

97. Interleaving String

难度: Hard

刷题内容

原题连接

内容描述

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

解题方案

思路 1 - 时间复杂度: O(2 ^ (m+n))- 空间复杂度: O(m+n)******

递归+双指针, 超时

class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        if len(s1) + len(s2) != len(s3):
            return False
        def helper(i, j):
            if i == len(s1) and j == len(s2):
                return True
            res = False
            if i < len(s1) and s1[i] == s3[i+j]:
                res |= helper(i+1, j)
            if j < len(s2) and s2[j] == s3[i+j]:
                res |= helper(i, j+1)
            return res
        return helper(0, 0)

加个cache就可以了

from functools import lru_cache

class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        if len(s1) + len(s2) != len(s3):
            return False
        @lru_cache(None)
        def helper(i, j):
            if i == len(s1) and j == len(s2):
                return True
            res = False
            if i < len(s1) and s1[i] == s3[i+j]:
                res |= helper(i+1, j)
            if j < len(s2) and s2[j] == s3[i+j]:
                res |= helper(i, j+1)
            return res
        return helper(0, 0)

思路 2 - 时间复杂度: O(m * n)- 空间复杂度: O(m * n)******

dp[i][j]代表s1的前i个字符和s2的前j个字符合起来是否能够组成s3的前i+j个字符

class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        if len(s1) + len(s2) != len(s3):
            return False
        dp = [[False] * (len(s2)+1) for _ in range(len(s1)+1)]
        dp[0][0] = True
        for i in range(1, len(s1)+1):
            if s1[i-1] == s3[i-1]:
                dp[i][0] = True
            else:
                break
        for j in range(1, len(s2)+1):
            if s2[j-1] == s3[j-1]:
                dp[0][j] = True
            else: # 前面都不符合了,后面肯定不符合了
                break
        for i in range(1, len(s1)+1):
            for j in range(1, len(s2)+1):
                if (dp[i-1][j] and s1[i-1] == s3[i-1+j]) or (dp[i][j-1] and s2[j-1] == s3[i+j-1]):
                    dp[i][j] = True
        return dp[-1][-1]