Skip to content

Latest commit

 

History

History
64 lines (43 loc) · 1.41 KB

97. Interleaving String (hard).md

File metadata and controls

64 lines (43 loc) · 1.41 KB

97. Interleaving String (hard)

https://leetcode.com/problems/interleaving-string/

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

Example 1:

img

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
  • s1, s2, and s3 consist of lower-case English letters.

代码

class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        if len(s3) != len(s1) + len(s2): return False
        m, n = len(s1), len(s2)
        dp = [[True for _ in range(n+1)] for _ in range(m+1)]
        for i in range(m+1):
            for j in range(n+1):
                if i==0 and j==0: dp[i][j] = True
                elif i == 0:
                    # first row
                    dp[i][j] = dp[i][j-1] and s2[j-1] == s3[i+j-1]
                elif j == 0:
                    # first col
                    dp[i][j] = dp[i-1][j] and s1[i-1] == s3[i+j-1]
                else:
                    dp[i][j] = (dp[i][j-1] and s2[j-1] == s3[i+j-1]) or (dp[i-1][j] and s1[i-1] == s3[i+j-1])
		
        return dp[m][n]