1759. Count Number of Homogenous Substrings
Description
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.
Solutions
Solution: Math
- Time complexity: O(n)
- Space complexity: O(1)
JavaScript
js
/**
* @param {string} s
* @return {number}
*/
const countHomogenous = function (s) {
const MODULO = 10 ** 9 + 7;
let result = (count = 0);
for (let index = 0; index <= s.length; index++) {
if (!index || s[index] === s[index - 1]) {
count += 1;
continue;
}
result += ((count + 1) * count) / 2;
result %= MODULO;
count = 1;
}
return result;
};