Skip to content

1759. Count Number of Homogenous Substrings 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  int countHomogenous(string s) {
    constexpr int kMod = 1'000'000'007;
    int ans = 0;
    int count = 0;
    char currentChar = '@';

    for (const char c : s) {
      count = c == currentChar ? count + 1 : 1;
      currentChar = c;
      ans += count;
      ans %= kMod;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int countHomogenous(String s) {
    final int kMod = 1_000_000_007;
    int ans = 0;
    int count = 0;
    char currentChar = '@';

    for (final char c : s.toCharArray()) {
      count = c == currentChar ? count + 1 : 1;
      currentChar = c;
      ans += count;
      ans %= kMod;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def countHomogenous(self, s: str) -> int:
    kMod = 1_000_000_007
    ans = 0
    count = 0
    currentChar = '@'

    for c in s:
      count = count + 1 if c == currentChar else 1
      currentChar = c
      ans += count
      ans %= kMod

    return ans