【LeetCode】1180. Count Substrings with Only One Distinct Letter 解题报告(C++)
2024-10-16 10:28:41
- 作者: 负雪明烛
- id: fuxuemingzhu
- 个人博客:http://fuxuemingzhu.cn/
题目地址:https://leetcode-cn.com/problems/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.
题目大意
给你一个字符串 S,返回只含 单一字母 的子串个数。
解题方法
组合数
从一段长度为n的单一字母字符串中,分别选择出长度为1,2,3,…,n的子串,共有n * (n + 1) / 2
个结果。
因此,遍历字符串,分别统计出单一字母字符串的长度,累加所有结果即可。
C++代码如下:
class Solution {
public:
int countLetters(string S) {
if (S.empty()) return 0;
int count = 1;
int res = 0;
char cur = S[0];
cout << endl;
for (int i = 1; i <= S.size(); ++i) {
if (i == S.size() || S[i] != cur) {
res += count * (count + 1) / 2;
cur = S[i];
count = 1;
} else {
count ++;
}
}
return res;
}
};
日期
2019 年 9 月 18 日 —— 今日又是九一八
最新文章
- winform中的确定取消
- javadoc相关问题
- JavaScript 堆内存分析新工具 OneHeap
- Sharepoint 2013 安装部署系列篇 第二篇 -- SQL集群安装
- eclipse 安装scons
- hdu 4670 树的点分治
- button倒计时可点击
- asp.net连接mysql数据库
- 学习笔记_JDBC_1_Demo1_连接数据库的基本操作和步骤
- Asp.net中具体的日期格式化用法
- SELECT 场 FROM 表 WHERE 字段 Like 条件
- linux_创建用户_copy远程文件_解压缩_执行
- android adb shell 命令大全
- 洛谷 P1226 【模板】快速幂||取余运算
- 外网访问ARM嵌入式Linux系统
- 安装ucenter以及单点实现
- P4574 [CQOI2013]二进制A+B
- 【xsy3355】图 思维
- ex:Could not load file or assembly &#39;System.Web.Helpers, Version=2.0.0.0, Culture=neutral, . 系统找不到指定的文件。
- bestcoder#23 1001 Sequence