#C++初学记录(判断子串#数学结合)
A Count Task
Problem Description
Count is one of WNJXYK’s favorite tasks. Recently, he had a very long string and he wondered that how many substrings which contains exactly one kind of lowercase in this long string. But this string is so long that he had kept counting for several days. His friend Kayaking wants to help him, so he turns to you for help.
Input
The input starts with one line contains exactly one positive integer T which is the number of test cases.
Each test case contains one line with a string which you need to do a counting task on.
Output
For each test case, output one line containing “y” where y is the number of target substrings.
Sample Input
3
qwertyuiop
qqwweerrttyyuuiioopp
aaaaaaaaaa
Sample Output
10
30
55
Hint
1<=T<=20,1<=len(string)<=10^5,1<=∑len(string)<=10^5
Strings only contain lowercase English letters.
正确代码
#include<iostream> #include<cstring> using namespace std; int main() { long long n=0,j=0; char a[100000]; cin>>n; while(n--) { long long count=1,ret=0; cin>>a; long long lena=strlen(a); for(int i=0;i<lena;i++) { if(a[i]==a[i+1]) { count++; } else if (a[i]!=a[i+1]) { ret+=count*(count+1)/2; count=1; } } cout<<ret<<endl; } return 0; }
题意理解
输入一个字符串,求它有多少个子字符串只包含一种小写字母。比如aaaa4个a,那么选一个有4种,选两个有3种,选三个有2种,选四个有1种,和为4+3+2+1。先进行一次遍历,统计他相同的小写字母个数,再利用等差数列公式求和。
错误以及调试
这类题型调试可以直观的看出错误点,主要程序是进行相同字符的子串字符个数判断,即
for(int i=0;i<lena;i++) { if(a[i]==a[i+1]) { count++; } else if (a[i]!=a[i+1]) { ret+=count*(count+1)/2; count=0; } }
因为运行计算错误所以我进行调试
结果是因为count的初始化赋值错误,应该以1初始化,因为程序在两个不相同的字符判断中会自动跳过一次程序使得本应该判断三次的count仅仅++两次,所以,以1初始化就能解决该问题。
最后运行成功截图。
- 点赞
- 收藏
- 分享
- 文章举报
- #C++初学记录(set进阶#acm cf 190802 B. Subsegments)
- C++判断语句(闰年的判断)(用switch语句完成具体某月的天数的计算(结合闰年的计算))
- #C++初学记录(ACM8-6-cf-f题)
- C++ opencv数学方法判断点是否在三角形内
- 探索c++的函数pow()的实现方法·数学与程序设计的结合(zz)
- 探索c++的函数pow()的实现方法·数学与程序设计的结合(zz)
- #C++初学记录(算法效率与度量)
- 初学C++基本知识记录
- #初学c++笔记心得记录
- #C++初学记录(STL容器以及迭代器)
- #C++初学记录(树和二叉树)
- #C++初学记录(typedef和define)
- C++初学初练数学指针与字符串之矩阵初练
- 探索c++的函数pow()的实现方法·数学与程序设计的结合
- 【嵌入式系统学习记录】练习:判断一个字符串是不是另一个字符串的子串;(比如"ab"是"aabcd"的子串)
- C++知识点之string,结合华为编程题:简单错误记录分析(附加容器pair知识点)
- c++数学函数运算,浮点数据相等判断
- 探索c++的函数pow()的实现方法·数学与程序设计的结合(绝对原创)
- C++ 判断字符串是否为子串
- 初学c++的一些小记录(Mac下)