甘肅做網(wǎng)站哪家專業(yè)推廣計(jì)劃方案模板
總時(shí)間限制: 1000ms 內(nèi)存限制: 65536kB
描述
求一個(gè)字符串中最長的連續(xù)出現(xiàn)的字符,輸出該字符及其出現(xiàn)次數(shù),字符串中無空白字符(空格、回車和tab),如果這樣的字符不止一個(gè),則輸出第一個(gè)
輸入
首先輸入N,即測試數(shù)據(jù)的組數(shù)
每組測試數(shù)據(jù)輸入:
一行,一個(gè)不包含空白字符的字符串,字符串長度小于200
輸出
一行,輸出最長的連續(xù)出現(xiàn)的字符及其出現(xiàn)次數(shù),中間用空格隔開
樣例輸入
2
aaaaabbbbbcccccccdddddddddd
abcdefghigk
樣例輸出
d 10
a 1
思路
遍歷字符串,記錄當(dāng)前字符和出現(xiàn)次數(shù),如果當(dāng)前字符和上一個(gè)字符相同,次數(shù)加一,否則比較當(dāng)前次數(shù)和最大次數(shù),如果當(dāng)前次數(shù)大于最大次數(shù),更新最大次數(shù)和字符,最后輸出最大次數(shù)和字符。
其實(shí),一開始我想使用map來解決,但是碰到了一些記錄上的問題,所以最后還是使用了pair來解決。用map倒像是將問題復(fù)雜化了。
這其實(shí)就是一個(gè)簡單的遍歷+獲取最大值的問題。
感謝xcdq的博文
Code
C++
#include <bits/stdc++.h>
using namespace std;int main() {int N;cin >> N;for(int i = 1; i <= N; i++) {string str;pair<char, int> tmp (0, 0), max (0, 0);cin >> str;for(long long unsigned int j = 0; j < str.size(); j++) {if(tmp.first == str[j]) tmp.second++;else {if(tmp.second > max.second) {max.second = tmp.second;max.first = tmp.first;}tmp.second = 1;tmp.first = str[j];}}if(tmp.second > max.second) {max.second = tmp.second;max.first = tmp.first;}cout << max.first << " " << max.second << endl;}
}
C
#include <stdio.h>
#include <string.h>int main() {int N;scanf("%d", &N);for(int i = 1; i <= N; i++) {char str[200];char tmp = 0, max = 0;int count = 0, max_count = 0;scanf("%s", str);for(int j = 0; j < strlen(str); j++) {if(tmp == str[j]) count++;else {if(count > max_count) {max_count = count;max = tmp;}count = 1;tmp = str[j];}}if(count > max_count) {max_count = count;max = tmp;}printf("%c %d\n", max, max_count);}
}