[LeetCode] Count Substrings Without Repeating Character

2743. Count Substrings Without Repeating Character

You are given a string s consisting only of lowercase English letters. We call a substring special if it contains no character which has occurred at least twice (in other words, it does not contain a repeating character). Your task is to count the number of special substrings. For example, in the string "pop", the substring "po" is a special substring, however, "pop" is not special (since 'p' has occurred twice).

Return the number of special substrings.

A substring is a contiguous sequence of characters within a string. For example, "abc" is a substring of "abcd", but "acd" is not.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int numberOfSpecialSubstrings(string s) {
vector<int> freq(26);
int res = 0, l = 0, r = 0, n = s.length();
while(r < n) {
while(r < n and freq[s[r] - 'a'] == 0) {
res += (r - l + 1);
freq[s[r++] - 'a'] += 1;
}
while(r < n and freq[s[r] - 'a'] == 1) {
freq[s[l++]-'a'] -= 1;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/06/30/PS/LeetCode/count-substrings-without-repeating-character/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.