#C++初学记录(判断子串#数学结合)

博客围绕字符串子串计数问题展开,输入字符串,求只含一种小写字母的子串数量,可通过遍历统计相同小写字母个数,用等差数列公式求和。调试时发现因count初始化赋值错误导致计算有误,将其以1初始化解决问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
            }
            
        }

因为运行计算错误所以我进行调试
1498728-20190530192645538-1149544310.png

结果是因为count的初始化赋值错误,应该以1初始化,因为程序在两个不相同的字符判断中会自动跳过一次程序使得本应该判断三次的count仅仅++两次,所以,以1初始化就能解决该问题。
最后运行成功截图。
1498728-20190530192940170-1217465015.png

转载于:https://www.cnblogs.com/xiaofengqaq/p/10951582.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值