HDU - 6480 A Count Task

题目要求:求出字符串中只有一种字母的子串个数。
我们只需要找到符合要求的最长的子串,然后用等差数列求和来计算即可。
注意事项:题干说字符串很长,因此我们需要很快反应到要用long long来存储数据。

#include <stdio.h>
#include <string.h>
char s[100005];
int main(void) {
    
    
	int T;
	scanf("%d", &T);
	while(T--) {
    
    
		memset(s, 0, sizeof(s));
		scanf("%s", s);
		int len = strlen(s);
		long long ans = 0; 
		for(int i=0; i<len; i++) {
    
    
			long long cnt = 1;  //字符本身也要算在计数里面,所以初始化为 1 
			while(s[i]==s[i+1] && s[i+1]!=0) {
    
    
				cnt++;
				i++;
			}
			ans += (1+cnt)*cnt/2;  //等差数列求和
		}
		printf("%lld\n", ans);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_51250927/article/details/113773994