[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 @   CNoodle  阅读(585)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示