[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 count = 1;
 4         int res = 1;
 5         for (int i = 1; i < S.length(); i++) {
 6             if (S.charAt(i) != S.charAt(i - 1)) {
 7                 count = 1;
 8             } else {
 9                 count++;
10             }
11             res += count;
12         }
13         return res;
14     }
15 }

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

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/13344658.html