1876. 长度为三且各字符不同的子字符串
C代码:滑动窗口
// 存在三种字符,且不重复、子串数量
int countGoodSubstrings(char * s){
int k = 3;
int hash[26] = {0};
int len = 0;
int l = 0;
int ans = 0;
for (int i = 0; i < strlen(s); ++i) {
hash[s[i] - 'a']++;
if (hash[s[i] - 'a'] == 1) {
++len;
}
while (hash[s[i] - 'a'] > 1 || len > k) {
hash[s[l] - 'a']--;
if (hash[s[l] - 'a'] == 0) {
--len;
}
++l;
}
if (len == k) {
++ans;
}
}
return ans;
}
C代码:规定了次数,一次遍历判断三个元素两两不等
// 存在三种字符,且不重复、子串数量
int countGoodSubstrings(char * s){
int res = 0;
int n = strlen(s);
for (int i = 0; i < n - 2; ++i){
if (s[i] != s[i+1] && s[i] != s[i+2] && s[i+1] != s[i+2]) {
++res;
}
}
return res;
}