题目描述
求一个字符串中最长的连续出现的字符,输出该字符及其出现次数,字符串中无空白字符(空格、回车和tab),如果这样的字符不止一个,则输出第一个。
输入样例
2
aaaaabbbbbcccccccdddddddddd
abcdefghigk
输出样例
d 10
a 1
算法
使用while循环将每个连续相同字符的字符串分割出来
C++ 代码
#include<iostream>
#include<string>
using namespace std;
int main(void)
{
string a,t,ans;
int n,len=0;
cin>>n;
while(n--)
{
cin>>a;
t+=a[0];
for(int i=1;i<=a.size()-1;i++)
{
while(a[i]==t[0] && i<=a.size()-1)//把连续相同的字符分割成单独的字符串
{
t+=a[i];
i++;
}
if(t.size()>len)
{
len=t.size();
ans=t;
}
t="";//字符串t初始化
if(i<=a.size()-1) t+=a[i];//排除最后一位时多输入\0导致占位
}
cout<<ans[0]<<" "<<len<<endl;
t="";//再次初始化t字符串,防止只剩最后一位输入进t导致占位
ans="";
len=0;
}
return 0;
}