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初始化就能解决该问题。
    最后运行成功截图。

  • 相关阅读:
    Win7下通过eclipse远程连接CDH集群来执行相应的程序以及错误说明
    Java中的Scanner类和String类
    java的eclipse操作和常用类Object的使用
    如何利用Cloudera Manager来手动安装parcel包
    java.io.IOException: Too many open files
    java中的包以及内部类的介绍
    HDFS中的checkpoint( 检查点 )的问题
    HDFS中Java的API使用测试
    利用ClouderaManager启动HBase时,出现 master.TableNamespaceManager: Namespace table not found. Creating...
    MapReducer程序调试技巧
  • 原文地址:https://www.cnblogs.com/xiaofengqaq/p/10951582.html
Copyright © 2011-2022 走看看