給定只包含小寫字母的字串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;
}
};