• #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)<=105,1<=∑len(string)<=105
    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初始化就能解决该问题。
    最后运行成功截图。

  • 相关阅读:
    中国省市区县最新数据表
    Android基础之退出键及menu不能使用
    对Hello China操作系统比较客观的评价
    对操作系统开发相关的一些问题的思考
    2010年9月12日周日_Builing your first mobile application_1.3
    2010年9月13日周一_WorkingWithSpatialReferences_6.2
    2010年9月04日_周六_Mobile Developmnet Environmnet_1
    2010年9月05日_周日_DeveloperEnvironmentRequirements_1.1
    2010年9月02日周四_Deploying to Mobile Devices_4.2
    2010年9月16日周四_Working with geometry_6.3
  • 原文地址:https://www.cnblogs.com/xiaofengqaq/p/10951582.html
Copyright © 2020-2023  润新知