Leetcode-2953

Count Complete Substrings

2953. Count Complete Substrings

You are given a string word and an integer k.

A substring s of word is complete if:

  • Each character in s occurs exactly k times.
  • The difference between two adjacent characters is at most 2. That is, for any two adjacent characters c1 and c2 in s, the absolute difference in their positions in the alphabet is at most 2.

Return the number of complete substrings of word.

A substring is a non-empty contiguous sequence of characters in a string.

Example 1:

Input: word = "igigee", k = 2 Output: 3 Explanation: The complete substrings where each character appears exactly twice and the difference between adjacent characters is at most 2 are: igigee, igigee, igigee.

Example 2:

Input: word = "aaabbbccc", k = 3 Output: 6 Explanation: The complete substrings where each character appears exactly three times and the difference between adjacent characters is at most 2 are: aaabbbccc, aaabbbccc, aaabbbccc, aaabbbccc, aaabbbccc, aaabbbccc.

Constraints:

  • 1 <= word.length <= 10^5
  • word consists only of lowercase English letters.
  • 1 <= k <= word.length
 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
45
46
#include <iostream>
#include <cstring>

class Solution {
public:
    int countCompleteSubstrings(std::string word, int k) {
        int n = word.length(), res = 0;
        int left = 0;
        for (int right = 1; right < n; ++right) {
            if (std::abs(word[right] - word[right - 1]) > 2) {
                res += countComplete(word.substr(left, right - left), k);
                left = right;
            }
        }
        res += countComplete(word.substr(left, n - left), k);
        return res;
    }

private:
    bool isComplete(int* times, int k) {
        for (int i = 0; i < 26; ++i) {
            if (times[i] && times[i] != k) {
                return false;
            }
        }
        return true;
    }
    
    int countComplete(std::string word, int k) {
        int n = word.size(), num = 0;
        int maxw = std::min(n, 26 * k);
        for (int w = k; w <= maxw; w += k) {
            int times[26] = { 0 };
            for (int i = 0; i < w; ++i) {
                ++times[word[i] - 'a'];
            }
            num += isComplete(times, k);
            for (int i = w; i < n; ++i) {
                ++times[word[i] - 'a'];
                --times[word[i - w] - 'a'];
                num += isComplete(times, k);
            }
        }
        return num;
    }
};

Leetcode-2953