简繁EN

LeetCodeNo. 041

【LeetCode with Python】 97. Interleaving String

目錄

題目

原題頁面:https://leetcode.com/problems/interleaving-string/
題目型別:Dynamic Programming, String
難度評價: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.


分析

比較常規的一道字串DP問題。注意檢查傳入引數,可以加速某些極端case的檢測速度。此外還可以用兩個row代替一個完整的二維矩陣,節約空間消耗。


程式碼

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]

本文地址:https://xnerv.wang/zh-tw/leetcode-interleaving-string/