97. Interleaving String

这篇博客探讨了一种中等难度的字符串问题——交错字符串。给出三个字符串s1, s2和s3,判断s3是否能由s1和s2的交错组合形成。作者提供了两种解决方案,一种是通过遍历s3并比较s1和s2的字符来实现,另一种是使用动态规划的方法。这两种方法的时间复杂度分别为O(n)和O(nm),空间复杂度分别为O(1)和O(nm)。博客包含了多个测试用例来验证解法的正确性。

97. Interleaving String

Medium

2701133Add to ListShare

Given strings s1s2, and s3, find whether s3 is formed by an interleaving of s1 and s2.

An interleaving of two strings s and t is a configuration where they are divided into non-empty substrings such that:

  • s = s1 + s2 + ... + sn
  • t = t1 + t2 + ... + tm
  • |n - m| <= 1
  • The interleaving is s1 + t1 + s2 + t2 + s3 + t3 + ... or t1 + s1 + t2 + s2 + t3 + s3 + ...

Note: a + b is the concatenation of strings a and b.

Example 1:

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

Example 2:

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

Example 3:

Input: s1 = "", s2 = "", s3 = ""
Output: true

Constraints:

  • 0 <= s1.length, s2.length <= 100
  • 0 <= s3.length <= 200
  • s1s2, and s3 consist of lowercase English letters.

Follow up: Could you solve it using only O(s2.length) additional memory space?

错误解法

class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        """
        # gg
        assert Solution().isInterleave("aa", "ab", "aaba")

        # AC
        assert Solution().isInterleave("", "b", "b")
        assert Solution().isInterleave("aa", "aa", "aaaa")
        assert Solution().isInterleave("aabcc", "dbbca", "aadbbcbcac")
        assert not Solution().isInterleave("aabcc", "dbbca", "aadbbbaccc")
        assert Solution().isInterleave("", "", "")

        解题思路:遍历s3,不断比较s1,s2当前索引位置的字符,若都相同则一直比较直到不同。
        时间复杂度:O(n),空间复杂度:O(1)
        """
        if len(s1) + len(s2) != len(s3):
            return False
        if len(s1) == 0:
            return s2 == s3
        if len(s2) == 0:
            return s1 == s3
        i = offset = index1 = index2 = 0
        while index1 + offset < len(s1) and index2 + offset < len(s2):
            if s1[index1 + offset] != s3[i] and s2[index2 + offset] != s3[i]:
                return False
            if s1[index1 + offset] == s3[i] and s2[index2 + offset] == s3[i]:
                offset += 1
                i += 1
                continue
            if s1[index1 + offset] == s3[i]:
                index1 += (offset + 1)
            if s2[index2 + offset] == s3[i]:
                index2 += (offset + 1)
            i += 1
            offset = 0
        # s3剩余字符串
        str = s3[-(len(s3) - i)]
        return str == s1[-(len(s1) - index1)] or str == s2[-(len(s2) - index2)]

 

AC

class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        """
        assert not Solution().isInterleave("ab", "ccd", "acdab")
        assert Solution().isInterleave("aa", "ab", "aaba")
        assert Solution().isInterleave("", "b", "b")
        assert Solution().isInterleave("aa", "aa", "aaaa")
        assert Solution().isInterleave("aabcc", "dbbca", "aadbbcbcac")
        assert not Solution().isInterleave("aabcc", "dbbca", "aadbbbaccc")
        assert Solution().isInterleave("", "", "")

        解题思路:看成一个二维地图,从左上角能不能走到右下角。
        时间复杂度:O(nm),空间复杂度:O(nm)

        如:("aa", "ab", "aaba")
        X 0 a b
        0 T T F
        a T T T
        a T F T
        """
        n1, n2, n3 = len(s1), len(s2), len(s3)
        if n1 + n2 != n3:
            return False
        if n1 == 0:
            return s2 == s3
        if n2 == 0:
            return s1 == s3
        dp = [[True for col in range(n2 + 1)] for row in range(n1 + 1)]
        for i in range(1, n1 + 1):
            dp[i][0] = dp[i - 1][0] and s1[i - 1] == s3[i - 1]
        for i in range(1, n2 + 1):
            dp[0][i] = dp[0][i - 1] and s2[i - 1] == s3[i - 1]
        for i in range(1, n1 + 1):
            for j in range(1, n2 + 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[n1][n2]
1. Two Sum 2. Add Two Numbers 3. Longest Substring Without Repeating Characters 4. Median of Two Sorted Arrays 5. Longest Palindromic Substring 6. ZigZag Conversion 7. Reverse Integer 8. String to Integer (atoi) 9. Palindrome Number 10. Regular Expression Matching 11. Container With Most Water 12. Integer to Roman 13. Roman to Integer 14. Longest Common Prefix 15. 3Sum 16. 3Sum Closest 17. Letter Combinations of a Phone Number 18. 4Sum 19. Remove Nth Node From End of List 20. Valid Parentheses 21. Merge Two Sorted Lists 22. Generate Parentheses 23. Swap Nodes in Pairs 24. Reverse Nodes in k-Group 25. Remove Duplicates from Sorted Array 26. Remove Element 27. Implement strStr() 28. Divide Two Integers 29. Substring with Concatenation of All Words 30. Next Permutation 31. Longest Valid Parentheses 32. Search in Rotated Sorted Array 33. Search for a Range 34. Find First and Last Position of Element in Sorted Array 35. Valid Sudoku 36. Sudoku Solver 37. Count and Say 38. Combination Sum 39. Combination Sum II 40. First Missing Positive 41. Trapping Rain Water 42. Jump Game 43. Merge Intervals 44. Insert Interval 45. Unique Paths 46. Minimum Path Sum 47. Climbing Stairs 48. Permutations 49. Permutations II 50. Rotate Image 51. Group Anagrams 52. Pow(x, n) 53. Maximum Subarray 54. Spiral Matrix 55. Jump Game II 56. Merge k Sorted Lists 57. Insertion Sort List 58. Sort List 59. Largest Rectangle in Histogram 60. Valid Number 61. Word Search 62. Minimum Window Substring 63. Unique Binary Search Trees 64. Unique Binary Search Trees II 65. Interleaving String 66. Maximum Product Subarray 67. Binary Tree Inorder Traversal 68. Binary Tree Preorder Traversal 69. Binary Tree Postorder Traversal 70. Flatten Binary Tree to Linked List 71. Construct Binary Tree from Preorder and Inorder Traversal 72. Construct Binary Tree from Inorder and Postorder Traversal 73. Binary Tree Level Order Traversal 74. Binary Tree Zigzag Level Order Traversal 75. Convert Sorted Array to Binary Search Tree 76. Convert Sorted List to Binary Search Tree 77. Recover Binary Search Tree 78. Sum Root to Leaf Numbers 79. Path Sum 80. Path Sum II 81. Binary Tree Maximum Path Sum 82. Populating Next Right Pointers in Each Node 83. Populating Next Right Pointers in Each Node II 84. Reverse Linked List 85. Reverse Linked List II 86. Partition List 87. Rotate List 88. Remove Duplicates from Sorted List 89. Remove Duplicates from Sorted List II 90. Intersection of Two Linked Lists 91. Linked List Cycle 92. Linked List Cycle II 93. Reorder List 94. Binary Tree Upside Down 95. Binary Tree Right Side View 96. Palindrome Linked List 97. Convert Binary Search Tree to Sorted Doubly Linked List 98. Lowest Common Ancestor of a Binary Tree 99. Lowest Common Ancestor of a Binary Search Tree 100. Binary Tree Level Order Traversal II
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值