97. 交错字符串

Hard

思路

这种字符串类型的题目我们之前做过几道,使用动态规划的方式来求解。这道题同样也从动态规划的角度来思考问题

以上,尝试写一下代码,AC!

代码

python3

class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
      l1 = len(s1)
      l2 = len(s2)
      if l1 + l2 != len(s3):
        return False
      dp = [[ False for _ in range(l2 + 1)] for _ in range(l1 + 1)]
      dp[0][0] = True
      for i in range(1,l1 + 1):
        dp[i][0] = dp[i-1][0] and s1[i-1] is s3[i-1]
      
      for j in range(1,l2 + 1):
        dp[0][j] = dp[0][j-1] and s2[j-1] is s3[j-1]

      for i in range(1,l1 + 1):
        for j in range(1,l2 + 1):
          if s1[i-1] is s3[i+j-1] and dp[i-1][j] is True:
            dp[i][j] = True
          elif s2[j-1] is s3[i+j-1] and dp[i][j-1] is True:
            dp[i][j] = True
      return dp[-1][-1]