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

时间:2022-05-01 14:32:59

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]