zoukankan      html  css  js  c++  java
  • #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初始化就能解决该问题。
    最后运行成功截图。

  • 相关阅读:
    [转]IIS 6.0中配置HTTP Gzip压缩
    SmartPhone下解决rm、rmvb等格式电影播放的方案(参考意见)
    提取文件夹下所有文件,按类型进行提取
    重学JSP—设置CATALINA_HOME环境变量
    android学习笔记
    用myeclipse配置hibernate
    Java 回调函数 转自:http://blog.sina.com.cn/s/blog_48cf38890100go6x.html
    fastadmin单独控制编辑、删除按钮的展示和隐藏
    fastadmin导出图片
    php计算坐标距离
  • 原文地址:https://www.cnblogs.com/xiaofengqaq/p/10951582.html
Copyright © 2011-2022 走看看