[LeetCode] 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.

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
47
48
49
50

class Solution {
int helper(string& s, int k) {
int n = s.length();
vector<vector<int>> pre(n+1);
{
vector<int> freq(26);
pre[0] = freq;
for(int i = 0; i < s.length(); i++) {
freq[s[i]-'a'] += 1;
pre[i+1] = freq;
}
}
int res = 0;
for(int i = 0; i < s.length(); i++) {
for(int j = i + k; j <= s.length() and (j - i) / k <= 26; j += k) {
int t = (j - i) / k;
bool ok = true;
bool over = false;
for(int x = 0; x < 26; x++) {
int d = pre[j][x] - pre[i][x];
if(d == 0) continue;
if(d != k) ok = false;
if(d > k) over = true;
if(!ok) break;
if(d == k) t -= 1;
}
if(ok and t == 0) res += 1;
if(over) break;
}
}
return res;
}
public:
int countCompleteSubstrings(string word, int k) {
string now = "";
int res = 0;
for(auto& ch : word) {
if(now.size() == 0 or abs(now.back() - ch) <= 2) now.push_back(ch);
else {
res += helper(now,k);
now = "";
now.push_back(ch);
}
}
res += helper(now,k);
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/12/03/PS/LeetCode/count-complete-substrings/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.