AcWing 771. 字符串中最长的连续出现的字符
原题链接
中等
作者:
sergey
,
2023-02-09 09:10:57
,
所有人可见
,
阅读 109
第一种解法:数组
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; i ++ )
{
string s;
cin >> s;
char c = s[0];
int max = 0;
int cnt = 0;
for (int j = 0; j < s.size(); j ++ )
{
if (cnt > max)
{
c = s[j];
max = cnt;
}
if (s[j] == s[j + 1]) cnt ++;
else cnt = 0;
}
cout << c << ' ' << max + 1 << endl;
}
return 0;
}
第二种解法:双指针。
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
while (n --)
{
string s;
cin >> s;
int j = 0;
int cnt = 0;
char c;
for (int i = 0; i < s.size(); i ++ )
{
j = i;
while (j < s.size() && s[i] == s[j]) j ++;
if (j - i > cnt)
{
cnt = j - i;
c = s[i];
}
i = j - 1;
}
cout << c << ' ' << cnt << endl;
}
}