Skip to content

1180. Count Substrings with Only One Distinct Letter 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  int countLetters(string s) {
    int ans = 0;
    int dp = 0;         // the length of the running letter
    char letter = '@';  // the running letter

    for (const char c : s) {
      if (c == letter) {
        ++dp;
      } else {
        dp = 1;
        letter = c;
      }
      // Add the number of substrings ending in the current letter.
      ans += dp;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public int countLetters(String s) {
    int ans = 0;
    int dp = 0;        // the length of the running letter
    char letter = '@'; // the running letter

    for (final char c : s.toCharArray()) {
      if (c == letter) {
        ++dp;
      } else {
        dp = 1;
        letter = c;
      }
      // Add the number of substrings ending in the current letter.
      ans += dp;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def countLetters(self, s: str) -> int:
    ans = 0
    dp = 0  # the length of the running letter
    letter = '@'  # the running letter

    for c in s:
      if c == letter:
        dp += 1
      else:
        dp = 1
        letter = c
      ans += dp  # Add the number of substrings ending in the current letter.

    return ans