Problem Description
Given a string s, return the number of substrings that have only one distinct letter.
Key Insights
- The problem asks for counting substrings that consist of a single repeating letter.
- Instead of checking each substring individually, notice that any contiguous group of the same character contributes multiple valid substrings.
- For a group with n same characters, the number of valid substrings is given by n*(n+1)/2.
- The overall solution is simply to traverse the string, group the same consecutive characters, and sum up the counts based on the above formula.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string, since we traverse the string once. Space Complexity: O(1), as we use a fixed amount of extra space.
Solution
The solution involves iterating through the string while counting how many times the same character appears consecutively. Every time the character changes (or at the end of the string), we calculate the number of substrings using the formula n*(n+1)/2 for the current group. We then reset the count and continue with the next group. This approach uses simple arithmetic and a single loop through the string.