[LeetCode] Count Number of Homogenous Substrings

1759. Count Number of Homogenous Substrings

Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7.

A string is homogenous if all the characters of the string are the same.

A substring is a contiguous sequence of characters within a string.

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) {
if(s.length() == 0)
return 0;

long res = 0;
long mod = 1e9 + 7, cnt = 1;
for(int i = 0; i < s.length() - 1; i++, cnt++) {
if(s[i] != s[i+1]) {
res += cnt * (cnt + 1) / 2;
cnt = 0;
}
}
res += cnt * (cnt + 1) / 2;
return res % mod;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/02/14/PS/LeetCode/count-number-of-homogenous-substrings/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.