LeetCode 筆記 - 567. Permutation in String

題目在此 567. Permutation in String

給定兩個字串,請判斷 s1 的所有排列組合,是否有出現在 s2 裏面

解題思維

基本思維是不計算所有排列組合,而是計算字串的所有字母個數

而我們還可以進一步使用 Sliding Window 的方法
進一步減少重複的計算

程式碼

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:

if not s1:
return False

if len(s1) > len(s2):
return False

def check():
check = True
for s in target_map:
if s not in window.keys():
check = False
break
if target_map[s] != window[s]:
check = False
break
if check:
return True

target_size = len(s1)

target_map = dict()
for s in s1:
if s not in target_map:
target_map[s] = 0
target_map[s] += 1

window = dict()
for i in range(target_size):
if s2[i] not in window:
window[s2[i]] = 0
window[s2[i]] += 1

if check():
return True

for i in range(1, len(s2) - target_size + 1):

last_index = i + target_size - 1

window[s2[i - 1]] -= 1
if s2[last_index] not in window:
window[s2[last_index]] = 0
window[s2[last_index]] += 1

if check():
return True

return False

相關文章