Skip to content

Latest commit

 

History

History

1180

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

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.

Companies:
Virtu Financial, Amazon

Related Topics:
Math, String

Solution 1.

// OJ: https://leetcode.com/problems/count-substrings-with-only-one-distinct-letter/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    int countLetters(string s) {
        int i = 0, N = s.size(), ans = 0;
        while (i < N) {
            int start = i;
            while (i < N && s[i] == s[start]) ++i;
            int len = i - start;
            ans += (1 + len) * len / 2;
        }
        return ans;
    }
};