| comments | true | ||
|---|---|---|---|
| difficulty | 简单 | ||
| edit_url | https://github.com/doocs/leetcode/edit/main/solution/1100-1199/1180.Count%20Substrings%20with%20Only%20One%20Distinct%20Letter/README.md | ||
| rating | 1315 | ||
| source | 第 8 场双周赛 Q1 | ||
| tags |
|
给你一个字符串 s,返回 只含 单一字母 的子串个数 。
示例 1:
输入: s = "aaaba" 输出: 8 解释: 只含单一字母的子串分别是 "aaa", "aa", "a", "b"。 "aaa" 出现 1 次。 "aa" 出现 2 次。 "a" 出现 4 次。 "b" 出现 1 次。 所以答案是 1 + 2 + 4 + 1 = 8。
示例 2:
输入: s = "aaaaaaaaaa" 输出: 55
提示:
1 <= s.length <= 1000s[i]仅由小写英文字母组成
我们可以使用双指针,用指针
时间复杂度
class Solution:
def countLetters(self, s: str) -> int:
n = len(s)
i = ans = 0
while i < n:
j = i
while j < n and s[j] == s[i]:
j += 1
ans += (1 + j - i) * (j - i) // 2
i = j
return ansclass Solution {
public int countLetters(String s) {
int ans = 0;
for (int i = 0, n = s.length(); i < n;) {
int j = i;
while (j < n && s.charAt(j) == s.charAt(i)) {
++j;
}
ans += (1 + j - i) * (j - i) / 2;
i = j;
}
return ans;
}
}class Solution {
public:
int countLetters(string s) {
int ans = 0;
for (int i = 0, n = s.size(); i < n;) {
int j = i;
while (j < n && s[j] == s[i]) {
++j;
}
ans += (1 + j - i) * (j - i) / 2;
i = j;
}
return ans;
}
};func countLetters(s string) int {
ans := 0
for i, n := 0, len(s); i < n; {
j := i
for j < n && s[j] == s[i] {
j++
}
ans += (1 + j - i) * (j - i) / 2
i = j
}
return ans
}function countLetters(s: string): number {
let ans = 0;
const n = s.length;
for (let i = 0; i < n; ) {
let j = i;
let cnt = 0;
while (j < n && s[j] === s[i]) {
++j;
ans += ++cnt;
}
i = j;
}
return ans;
}class Solution:
def countLetters(self, s: str) -> int:
ans = 0
i, n = 0, len(s)
while i < n:
j = i
cnt = 0
while j < n and s[j] == s[i]:
j += 1
cnt += 1
ans += cnt
i = j
return ansclass Solution {
public int countLetters(String s) {
int ans = 0;
int i = 0, n = s.length();
while (i < n) {
int j = i;
int cnt = 0;
while (j < n && s.charAt(j) == s.charAt(i)) {
++j;
ans += ++cnt;
}
i = j;
}
return ans;
}
}class Solution {
public:
int countLetters(string s) {
int ans = 0;
int i = 0, n = s.size();
while (i < n) {
int j = i;
int cnt = 0;
while (j < n && s[j] == s[i]) {
++j;
ans += ++cnt;
}
i = j;
}
return ans;
}
};func countLetters(s string) (ans int) {
i, n := 0, len(s)
for i < n {
j := i
cnt := 0
for j < n && s[j] == s[i] {
j++
cnt++
ans += cnt
}
i = j
}
return
}