题目描述
求一个字符串中最长的连续出现的字符,输出该字符及其出现次数,字符串中无空白字符(空格、回车和tab),如果这样的字符不止一个,则输出第一个。
C++ 代码
#include <iostream>
#include <string>
using namespace std;
int main() {
int n;
cin >> n;
string s;
for (int i = 0; i < n; ++i) {
cin >> s;
if (s.empty()) continue;
char max_char = s[0];
int max_count = 1;
int current_count = 1;
for (size_t j = 1; j < s.size(); ++j) {
if (s[j] == s[j - 1]) {
++current_count;
} else {
if (current_count > max_count) {
max_count = current_count;
max_char = s[j - 1];
}
current_count = 1;
}
}
// 处理字符串末尾的情况
if (current_count > max_count) {
max_count = current_count;
max_char = s[s.size() - 1];
}
cout << max_char << " " << max_count << endl;
}
return 0;
}