Skip to content

Commit dcb2f7e

Browse files
committed
feat: solve No.1759
1 parent fa42f44 commit dcb2f7e

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# 1759. Count Number of Homogenous Substrings
2+
3+
- Difficulty: Medium.
4+
- Related Topics: Math, String.
5+
- Similar Questions: Consecutive Characters, Number of Substrings With Only 1s, Sum of Subarray Ranges, Count the Number of Good Subarrays.
6+
7+
## Problem
8+
9+
Given a string `s`, return **the number of **homogenous** substrings of **`s`**.** Since the answer may be too large, return it **modulo** `109 + 7`.
10+
11+
A string is **homogenous** if all the characters of the string are the same.
12+
13+
A **substring** is a contiguous sequence of characters within a string.
14+
15+
 
16+
Example 1:
17+
18+
```
19+
Input: s = "abbcccaa"
20+
Output: 13
21+
Explanation: The homogenous substrings are listed as below:
22+
"a" appears 3 times.
23+
"aa" appears 1 time.
24+
"b" appears 2 times.
25+
"bb" appears 1 time.
26+
"c" appears 3 times.
27+
"cc" appears 2 times.
28+
"ccc" appears 1 time.
29+
3 + 1 + 2 + 1 + 3 + 2 + 1 = 13.
30+
```
31+
32+
Example 2:
33+
34+
```
35+
Input: s = "xy"
36+
Output: 2
37+
Explanation: The homogenous substrings are "x" and "y".
38+
```
39+
40+
Example 3:
41+
42+
```
43+
Input: s = "zzzzz"
44+
Output: 15
45+
```
46+
47+
 
48+
**Constraints:**
49+
50+
51+
52+
- `1 <= s.length <= 105`
53+
54+
- `s` consists of lowercase letters.
55+
56+
57+
## Solution
58+
59+
```javascript
60+
/**
61+
* @param {string} s
62+
* @return {number}
63+
*/
64+
var countHomogenous = function(s) {
65+
var startIndex = 0;
66+
var sum = 0;
67+
var mod = Math.pow(10, 9) + 7;
68+
for (var i = 0; i < s.length; i++) {
69+
if (s[i] === s[i + 1]) continue;
70+
var num = i - startIndex + 1;
71+
sum += ((1 + num) * num / 2) % mod;
72+
sum %= mod;
73+
startIndex = i + 1;
74+
}
75+
return sum;
76+
};
77+
```
78+
79+
**Explain:**
80+
81+
nope.
82+
83+
**Complexity:**
84+
85+
* Time complexity : O(n).
86+
* Space complexity : O(1).

0 commit comments

Comments
 (0)