We want to count all substrings where at least one character appears at least k times. For large n, we can fix the character and use a sliding window to efficiently count substrings where that character appears at least k times. We sum this for all 26 lowercase letters.
classSolution {
publiclongcountSubstrings(String s, int k) {
int n = s.length();
long ans = 0;
for (char ch ='a'; ch <='z'; ++ch) {
int[] cnt =newint[26];
int l = 0;
for (int r = 0; r < n; ++r) {
cnt[s.charAt(r) -'a']++;
if (s.charAt(r) == ch && cnt[ch -'a']>= k) {
while (cnt[ch -'a']> k) {
cnt[s.charAt(l++) -'a']--;
}
ans += l + 1;
}
}
}
return ans;
}
}
classSolution {
funcountSubstrings(s: String, k: Int): Long {
val n = s.length
var ans = 0Lfor (ch in'a'..'z') {
val cnt = IntArray(26)
var l = 0for (r in0 until n) {
cnt[s[r] - 'a']++if (s[r] == ch && cnt[ch - 'a'] >= k) {
while (cnt[ch - 'a'] > k) {
cnt[s[l++] - 'a']-- }
ans += l + 1 }
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution:
defcountSubstrings(self, s: str, k: int) -> int:
n = len(s)
ans =0for ch in range(26):
cnt = [0] *26 l =0for r in range(n):
cnt[ord(s[r]) - ord('a')] +=1if ord(s[r]) - ord('a') == ch and cnt[ch] >= k:
while cnt[ch] > k:
cnt[ord(s[l]) - ord('a')] -=1 l +=1 ans += l +1return ans
impl Solution {
pubfncount_substrings(s: String, k: i32) -> i64 {
let n = s.len();
let s = s.as_bytes();
letmut ans =0i64;
for ch inb'a'..=b'z' {
letmut cnt =vec![0; 26];
letmut l =0;
for r in0..n {
cnt[(s[r] -b'a') asusize] +=1;
if s[r] == ch && cnt[(ch -b'a') asusize] >= k {
while cnt[(ch -b'a') asusize] > k {
cnt[(s[l] -b'a') asusize] -=1;
l +=1;
}
ans += (l +1) asi64;
}
}
}
ans
}
}