测评会员优惠活动进行中 · 开通 VIP,有效期内测评不限次 VIP 优惠中 · 测评不限次 立即查看

A41123. 字符串中最长的连续出现的字符

填空题 较难

题目描述

字符串中最长的连续出现的字符

题目描述

求一个字符串中最长的连续出现的字符,输出该字符及其出现次数。字符串中无空白字符(空格、回车和tab),如果这样的字符不止一个,则输出出现最早的字符。

输入格式

一行,一个不包含空白字符的字符串,字符串长度小于200。

输出格式

一行,输出最长的连续出现的字符及其最长的连续出现次数,中间以一个空格分开。

样例输入

aaaaadbbbbbcccccccdddddddddd

样例输出

d 10

参考答案

#include <iostream> #include <cstring> using namespace std; string s; int n; int main(){ cin>>n; for(int i=0;i<n;i++){ cin>>s; int len=s.length(); char c,max_c; int max=0; int num=0; for(int i=0;i<len;i++){ if(i==0){//第一个字符直接计数为1 num=1; c=s[0]; } else if(s[i]==s[i-1]){ if(i==len-1 && num+1>max){ //此时至最后一个字符,num+1才为此字符个数 max=num+1; max_c=c; } num++; //不跳出则num++ // cout<<c<<" "<<num<<endl; } else if(s[i]!=s[i-1]){ if(num>max){//判断,若大于最大数则更新 max=num; max_c=c; } c=s[i]; num=1;//重置num } } cout<<max_c<<" "<<max<<endl; } return 0; }
上一题 下一题