本代碼用C++的string類型直接建立一個字元串數組,額外建立一個count數組用來計數。
主要想法是采用兩兩比較的方法比較兩個字元串是否相等,如果相等的話則count[i]++。兩個循環都是從0開始,包含一次字元串的自我比較,讓count為1。
#include <iostream>
#include <string>
using namespace std;
int main(){
string color[1001];
int count[1001];
int flag=0;
int max=0;
int n;
while(scanf("%d", &n)!=EOF){
if (n==0)
break;
for(int i=0; i<n; i++){
count[i]=0;
}
for(int i=0; i<n; i++){
cin >> color[i];
}
for (int i=0; i<n; i++){
for (int j=0; j<n; j++){
if (color[i]==color[j])
count[i]+=1;
}
}
max = 0;
for(int i=0; i<n; i++){
if (count[i] > max){
max = count[i];
flag = i;
}
}
cout << color[flag] << endl;
}
return 0;
}