Skip to content

Commit

Permalink
add: (easy) 3258. 统计满足 K 约束的子字符串数量 I
Browse files Browse the repository at this point in the history
  • Loading branch information
KevenGe committed Nov 12, 2024
1 parent c3909c2 commit a558ebf
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
META:
ID: 3258
TITLE_CN: 统计满足 K 约束的子字符串数量 I
HARD_LEVEL: EASY
URL: https://leetcode.cn/problems/count-substrings-that-satisfy-k-constraint-i/
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
在该问题中,考虑到`1 <= s.length <= 50`,因此即使遍历所以的**子串**也只有$2500$数量级,大概率可以直接遍历。而且,可以通过**数据预处理**或者**滑动窗口**的方式进行优化子串的计算方式。
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
class Solution:
def countKConstraintSubstrings(self, s: str, k: int) -> int:

zero_accu = [0] * len(s)
zero_accu[0] = 1 if s[0] == "0" else 0
for i in range(1, len(s)):
zero_accu[i] = zero_accu[i - 1] + (1 if s[i] == "0" else 0)

one_accu = [0] * len(s)
one_accu[0] = 1 if s[0] == "1" else 0
for i in range(1, len(s)):
one_accu[i] = one_accu[i - 1] + (1 if s[i] == "1" else 0)

ans = 0
for i in range(len(s)):
for j in range(i, len(s)):
if i == 0:
a = zero_accu[j]
b = one_accu[j]
else:
a = zero_accu[j] - zero_accu[i - 1]
b = one_accu[j] - one_accu[i - 1]

if a <= k or b <= k:
ans += 1

return ans

0 comments on commit a558ebf

Please sign in to comment.