LC3298. 统计重新排列后包含另一个字符串的子字符串数目 II

题目链接:3298. 统计重新排列后包含另一个字符串的子字符串数目 II - 力扣(LeetCode)

题解

参考代码

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
class Solution:
def validSubstringCount(self, word1: str, word2: str) -> int:


ans = 0
b_cnt = defaultdict(int)
for s in word2:
b_cnt[s] += 1
n = len(word1)
a_cnt = defaultdict(int)
tmp = 0
st = 0
for i in range(0, n):

if tmp == len(word2):
break

st = i
a_cnt[word1[i]] += 1

if a_cnt[word1[i]] == b_cnt[word1[i]]:
tmp += b_cnt[word1[i]]

if tmp != len(word2):
return 0
ans = 0

tt = 0
while a_cnt[word1[tt]] - 1 >= b_cnt[word1[tt]]:
a_cnt[word1[tt]] -= 1
tt += 1

ans += tt + 1

for i in range(st+1, n):
# print(i, ans, tt)

a_cnt[word1[i]] += 1
while a_cnt[word1[tt]] - 1 >= b_cnt[word1[tt]]:
a_cnt[word1[tt]] -= 1
tt += 1
# a_cnt[word1[i]] += 1
ans += tt + 1
return ans

LC3298. 统计重新排列后包含另一个字符串的子字符串数目 II

https://blog.xiang578.com/problem/lc.html

作者

Ryen Xiang

发布于

2025-01-12

更新于

2025-01-12

许可协议


网络回响

评论