[LeetCode] Count Substrings with Only One Distinct Letter

1180. Count Substrings with Only One Distinct Letter

Given a string s, return the number of substrings that have only one distinct letter.

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
int countLetters(string s) {
int res = 0;
for(int l = 0, r = 0; r < s.length(); l = r) {
while(r < s.length() and s[l] == s[r]) r += 1;
res += (r - l) * (r - l + 1) / 2;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/07/30/PS/LeetCode/count-substrings-with-only-one-distinct-letter/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.