[LeetCode] 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.

统计只含单一字母的子串。

题意很直接,这里我想提一下怎么计算子串的长度。遍历 input 字符串,并一开始设置一个变量 count = 1。count = 1 是因为无论什么字母,只出现一次的时候,他本身也是一个子串。当之后出现同样字母的时候,count 就需要++,表明当前这个字母可以组成的最长的子串的长度。同时这时候记得要把此时的 count 累加到 res 里。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public int countLetters(String s) {
 3         int res = 0;
 4         int count = 0;
 5         char pre = s.charAt(0);
 6         for (int i = 0; i < s.length(); i++) {
 7             char cur = s.charAt(i);
 8             if (cur == pre) {
 9                 count++;
10             } else {
11                 res += (1 + count) * count / 2;
12                 count = 1;
13                 pre = cur;
14             }
15         }
16         // 如果一直都是同一个字母,这里也是需要再结算一次的
17         res += (1 + count) * count / 2;
18         return res;
19     }
20 }

 

JavaScript实现

 1 /**
 2  * @param {string} S
 3  * @return {number}
 4  */
 5 var countLetters = function(s) {
 6     let count = 1;
 7     let res = 0;
 8     for (let i = 0; i < s.length; i++) {
 9         if (s.charAt(i) != s.charAt(i - 1)) {
10             count = 1;
11         } else {
12             count++;
13         }
14         res += count;
15     }
16     return res;
17 };

 

相关题目

1180. Count Substrings with Only One Distinct Letter - 统计连续出现的相同字母

1513. Number of Substrings With Only 1s - 统计连续出现的1

1759. Count Number of Homogenous Substrings

LeetCode 题目总结

posted @ 2020-07-20 13:50  CNoodle  阅读(574)  评论(0编辑  收藏  举报