chenfy27的刷题记录

导航

< 2025年2月 >
26 27 28 29 30 31 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 1
2 3 4 5 6 7 8

leetcode2953 统计完全子字符串的数目

给定只包含小写字母的字符串word和整数k,如果s的某个子串中每个字符恰好出现k次,并且相邻字母最多相差2,则称其为完全字符串。求word中完全字符串的数目。
1<=word.length<=1e5; 1<=k<=word.length

预处理出每个字母出现次数的前缀和,这样可以O(1)得到区间[l,r]内某个字母的出现次数。然后分组循环得到满足相邻字母最多相差2的子区间,在上面枚举完全字符串的长度,只能是k,2k,3k,...26k,利用前缀和判断即可。

int cnt[100005][26];
class Solution {
public:
int countCompleteSubstrings(string word, int k) {
int n = word.size();
for (int i = 1; i <= n; i++) {
char z = word[i-1];
for (int j = 0; j < 26; j++) {
cnt[i][j] = cnt[i-1][j];
if (j == z-'a') {
cnt[i][j] += 1;
}
}
}
auto check = [&](int l, int r, int K) -> int {
l++, r++;
for (int i = 0; i < 26; i++) {
int z = cnt[r][i] - cnt[l-1][i];
if (z != 0 && z != K)
return 0;
}
return 1;
};
int ans = 0;
for (int i = 0, j; i < n; i = j) {
for (j = i+1; j < n && abs(word[j]-word[j-1]) <= 2; j++);
for (int z = 1; z <= 26; z++) {
int d = z * k;
for (int u = i; u+d <= j; u++) {
int v = u+d-1;
if (check(u,v,k)) {
ans += 1;
}
}
}
}
return ans;
}
};

posted on   chenfy27  阅读(4)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示