forked from mehul-1607/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_1180.java
49 lines (47 loc) · 1.28 KB
/
_1180.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.fishercoder.solutions;
/**
* 1180. Count Substrings with Only One Distinct Letter
*
* Given a string S, return the number of substrings that have only one distinct letter.
*
* Example 1:
* Input: S = "aaaba"
* Output: 8
* Explanation: The substrings with one distinct letter are "aaa", "aa", "a", "b".
* "aaa" occurs 1 time.
* "aa" occurs 2 times.
* "a" occurs 4 times.
* "b" occurs 1 time.
* So the answer is 1 + 2 + 4 + 1 = 8.
*
* Example 2:
* Input: S = "aaaaaaaaaa"
* Output: 55
*
* Constraints:
* 1 <= S.length <= 1000
* S[i] consists of only lowercase English letters.
* */
public class _1180 {
public static class Solution1 {
public int countLetters(String S) {
int count = 0;
for (int i = 0, j = 1; j < S.length() && i <= j; ) {
while (j < S.length() && S.charAt(i) == S.charAt(j)) {
j++;
}
count += countTimes(S.substring(i, j));
i += S.substring(i, j).length();
}
return count;
}
private int countTimes(String str) {
int len = str.length();
int times = 0;
while (len > 0) {
times += len--;
}
return times;
}
}
}