Problem
Given a strings, return the number of substrings that have only one distinct letter.
Examples
Constraints
- 1 <= s.length <= 1000
sconsists of only lowercase English letters.
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 1180 with 24 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 1180 # by problem number
lcpy gen -s count_substrings_with_only_one_distinct_letter # by problem name
s, return the number of substrings that have only one distinct letter.
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.
Input: s = "aaaaaaaaaa"
Output: 55
s consists of only lowercase English letters.class Solution:
# Time: O(n)
# Space: O(1)
def count_letters(self, s: str) -> int:
ans = 0
i = 0
n = len(s)
while i < n:
j = i
while j < n and s[j] == s[i]:
ans += j - i + 1
j += 1
i = j
return ans
| Time | Space |
|---|---|
| O(n) | O(1) |