[AcWing 771] 字符串中最长的连续出现的字符

image


点击查看代码
#include<iostream>

using namespace std;

string str;
int n;

int main()
{
    cin >> n;
    while (n --) {
        cin >> str;
        int cnt = 0;
        char c;
        for (int i = 0; i < str.size(); i++) {
            int j = i;
            while (j < str.size() && str[i] == str[j])  j++;
            if (j - i > cnt)    cnt = j - i, c = str[i];
            i = j - 1;
        }
        cout << c << ' ' << cnt << endl;
    }
    return 0;
}

使用双指针,当 j 未到字符串末尾并且 str[i] == str[j] 时, j++ ;
最长的长度 cnt = j - i ;
此时 j 位于一个新的字符,由于 for 循环时会执行 i++ ,所以让 i = j - 1;

posted @ 2022-04-14 11:23  wKingYu  阅读(56)  评论(0)    收藏  举报