题目地址: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. 1 <= S.length <= 1000
  2. 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 日 —— 今日又是九一八

最新文章

  1. winform中的确定取消
  2. javadoc相关问题
  3. JavaScript 堆内存分析新工具 OneHeap
  4. Sharepoint 2013 安装部署系列篇 第二篇 -- SQL集群安装
  5. eclipse 安装scons
  6. hdu 4670 树的点分治
  7. button倒计时可点击
  8. asp.net连接mysql数据库
  9. 学习笔记_JDBC_1_Demo1_连接数据库的基本操作和步骤
  10. Asp.net中具体的日期格式化用法
  11. SELECT 场 FROM 表 WHERE 字段 Like 条件
  12. linux_创建用户_copy远程文件_解压缩_执行
  13. android adb shell 命令大全
  14. 洛谷 P1226 【模板】快速幂||取余运算
  15. 外网访问ARM嵌入式Linux系统
  16. 安装ucenter以及单点实现
  17. P4574 [CQOI2013]二进制A+B
  18. 【xsy3355】图 思维
  19. ex:Could not load file or assembly &#39;System.Web.Helpers, Version=2.0.0.0, Culture=neutral, . 系统找不到指定的文件。
  20. bestcoder#23 1001 Sequence

热门文章

  1. shell 脚本在linux中的应用
  2. Augustus 进行基因注释
  3. Macbookpro快捷键
  4. 7本Python必读的入门书籍,你看过吗?(附福利)
  5. springcloud - alibaba快速上手 - 更新完毕
  6. 前端2 — CSS — 更新完毕
  7. Hadoop入门 集群时间同步
  8. 学习java 7.18
  9. Linux基础命令---mysqldump数据库备份
  10. OC-基础数据类型