简繁EN

LeetCodeNo. 041

[LeetCode with Python] 97. Interleaving String

Contents

Problem

Problem page: https://leetcode.com/problems/interleaving-string/
Topics: Dynamic Programming, String
Difficulty: Hard

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

For example,
Given:
s1 = "aabcc",
s2 = "dbbca",

When s3 = "aadbbcbcac", return true.
When s3 = "aadbbbaccc", return false.


Analysis

A pretty standard dynamic programming problem on strings. Checking the input parameters can help catch some edge cases faster. I use two rows instead of a full 2D matrix to save space.


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution:

# @return a boolean
def isInterleave(self, s1, s2, s3):
len1 = len(s1)
len2 = len(s2)
len3 = len(s3)

if len1 + len2 != len3:
return False
if 0 == len1:
return s2 == s3
if 0 == len2:
return s1 == s3

row1 = [False for col in range(len2 + 1)]
row1[0] = True
for i in range(1, len2 + 1):
row1[i] = ( row1[i - 1] and (s2[i - 1] == s3[i - 1]))

row2 = [False for col in range(len2 + 1)]

for m in range(1, len1 + 1):
row2[0] = (row1[0] and (s1[m - 1] == s3[m - 1]))
for n in range(1, len2 + 1):
k = m + n - 1
# why and ? because [m, n] maybe come from up or left, one of the two is the right source.
row2[n] = (s1[m - 1] == s3[k] and row1[n]) or (s2[n - 1] == s3[k] and row2[n - 1])
row1, row2 = row2, row1

return row1[len2]

Article link: https://xnerv.wang/en/leetcode-interleaving-string/