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.
Companies: Virtu Financial
Similar Questions:
- Consecutive Characters (Easy)
- Number of Substrings With Only 1s (Medium)
- Sum of Subarray Ranges (Medium)
- Count the Number of Good Subarrays (Medium)
Hints:
- A string of only 'a's of length k contains k choose 2 homogenous substrings.
- Split the string into substrings where each substring contains only one letter, and apply the formula on each substring's length.
// OJ: https://leetcode.com/problems/count-number-of-homogenous-substrings
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
int countHomogenous(string s) {
long N = s.size(), cnt = 0, ans = 0, mod = 1e9 + 7;
for (int i = 0; i < N; ++i) {
++cnt;
if (i == N - 1 || s[i + 1] != s[i]) {
ans = (ans + cnt * (cnt + 1) / 2 % mod) % mod;
cnt = 0;
}
}
return ans;
}
};