Count Substrings with Only One Distinct Letter Problem
Description
LeetCode Problem 1180.
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 <= 1000s[i]consists of only lowercase English letters.
Solution
Approach: Count Runs of Equal Letters
A substring with only one distinct letter lies entirely inside a run of equal letters, such as "aaa" in "aaaba". Different positions count as different substrings, even when the text is the same: "aaaba" has four substrings "a".
Walk through the string and keep run, the length of the run of equal letters ending at the current position: it grows by one when the letter repeats the previous one and resets to 1 otherwise. The substrings with one distinct letter that end here are exactly those that start inside this run, so there are run of them. Adding run at every position counts each substring once, by its end.
For "aaaba", run goes 1, 2, 3, 1, 1, for a total of 8. A run of length L contributes 1 + 2 + ... + L = L(L + 1) / 2 in total.
Complexity: O(n) time and O(1) extra space.
class Solution:
def countLetters(self, s: str) -> int:
total = 0
run = 0 # length of the run of equal letters ending at the current position
for i, ch in enumerate(s):
run = run + 1 if i > 0 and ch == s[i - 1] else 1
total += run # one new substring for each start inside the run
return total