1131. Count Substrings with Only One Distinct Letter
Difficulty: Easy
Topics: Math, String
Similar Questions:
Problem:
Given a string S
, return the number of substrings that have only one distinct letter.
Example 1:
Input: S = "aaaba" Output: 8 Explanation: The substrings with one distinct letter are "aaa", "aa", "a", "b". "aaa" occurs 1 time. "aa" occurs 2 times. "a" occurs 4 times. "b" occurs 1 time. So the answer is 1 + 2 + 4 + 1 = 8.
Example 2:
Input: S = "aaaaaaaaaa" Output: 55
Constraints:
1 <= S.length <= 1000
S[i]
consists of only lowercase English letters.
Solutions:
class Solution {
public:
int countLetters(string S) {
int count = 0;
int consecutive = 1;
for (int i = 1; i < S.length(); ++i) {
if (S[i] == S[i-1]) {
++consecutive;
} else {
count += calculate(consecutive);
consecutive = 1;
}
}
count += calculate(consecutive);
return count;
}
private:
int calculate(int num) {
return num * (num + 1) / 2;
}
};