[LeetCode] 97. Interleaving String_ Hard tag: Dynamic Programming

本文深入探讨了如何使用动态规划解决字符串s3是否由s1和s2交错组成的问题,通过构建二维数组mem来记录子问题的解决方案,最终确定s3是否能由s1和s2交错生成。

Given s1s2s3, 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
 
这个题目利用dynamic programming,mem[l1 + 1][l2 + 1]  #mem[i][j] means that whether the first i characters of s1 and the first j characters of s2 be able to make first i + j characters of s3. 
  mem[i][j] = (mem[i - 1][j] and s1[i - 1] == s3[i + j - 1])   # when the last character of s3 matches the last of s1
          or (mem[i][j - 1]) and s2[j - 1] == s3[i + j - 1])  # when the last character of s3 matches the last of s2
     initial: mem[i][0] = s1[:i] == s3[:i]
      mem[0][j] = s2[:j] == s3[:j]
 
code
class Solution:
    def interLeaveString(self, s1, s2, s3):
            l1, l2, l3 = len(s1), len(s2), len(s3)
            if l1 + l2 != l3: return False
            mem = [[False] * (l2 + 1) for _ in range(l1 + 1)]
            for i in range(l1 + 1):
                mem[i][0] = s1[:i] == s3[:i]
            for j in range(l2 + 1):
                mem[0][j] = s2[:j] == s3[:j]
            for i in range(1, 1 + l1):
                for j in range(1, 1 + l2):
                    mem[i][j] = (mem[i - 1][j] and s1[i - 1] == s3[i + j - 1]) or (mem[i][j - 1] and s2[j - 1] == s3[i + j - 1])
            return mem[l1][l2]

 

 

转载于:https://www.cnblogs.com/Johnsonxiong/p/10789615.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值