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

给定只包含小写字母的字符串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];
int init = []() {
    cin.tie(0)->sync_with_stdio(0);
    return 0;
}();
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 @ 2024-03-23 19:13  chenfy27  阅读(1)  评论(0编辑  收藏  举报