-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add: (easy) 3258. 统计满足 K 约束的子字符串数量 I
- Loading branch information
Showing
3 changed files
with
33 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
在该问题中,考虑到`1 <= s.length <= 50`,因此即使遍历所以的**子串**也只有$2500$数量级,大概率可以直接遍历。而且,可以通过**数据预处理**或者**滑动窗口**的方式进行优化子串的计算方式。 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |