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.
Example 1:
Input: s = "abbcccaa"
Output: 13
Explanation: The homogenous substrings are listed as below:
"a" appears 3 times.
"aa" appears 1 time.
"b" appears 2 times.
"bb" appears 1 time.
"c" appears 3 times.
"cc" appears 2 times.
"ccc" appears 1 time.
3 + 1 + 2 + 1 + 3 + 2 + 1 = 13.
Example 2:
Input: s = "xy"
Output: 2
Explanation: The homogenous substrings are "x" and "y".
Example 3:
Input: s = "zzzzz"
Output: 15
Constraints:
- 1 <= s.length <= 105
- s consists of lowercase letters.
Solution:
for n consecutive chars, c, cc, ccc, c...cc (n c's) appear 1 + 2 + 3 + ... + n times
class Solution {
int mod = (int) (1e9) + 7;
public int countHomogenous(String s) {
int n = s.length();
int[] sum = calc(n);
int count = 1;
int res = 0;
char prev = s.charAt(0);
for (int i = 1; i < n; i ++) {
char curr = s.charAt(i);
if (prev == curr) {
count ++;
} else {
// System.out.println(prev + ", " + count + ", " + sum[count]);
res = (res + sum[count]) % mod;
count = 1;
}
prev = curr;
}
res = (res + sum[count]) % mod;
return res;
}
public int[] calc(int n) {
int[] res = new int[n + 1];
res[0] = 0;
for (int i = 1; i <= n; i ++) {
res[i] = (res[i - 1] + i) % mod;
}
return res;
}
}