稍有意义的一道题:
要求输入一组字符串,找出其中的最大和最小的字符串,并找出其中出现次数最多的字符串mode。
思路:
输入完成后,先对字符串进行排序,然后做前后比较。
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
inline void keep_window_open() { char ch; cin >> ch; }
int main()
{
vector<string>s;
int hash[100] = {0};
for (string temp; cin >> temp;)//输入字符串
{
if (temp == "end")
break;
s.push_back(temp);
}
string max = s[0], min = s[0];
for (string x : s)//判断最大和最小的字符串
{
if (x > max)
max = x;
if (x < min)
min = x;
}
sort(s.begin(), s.end());
for (int i = 0,j=0; i < s.size()-1; i++)
{
if (s[i] == s[i + 1])//前后两元素进行比较
hash[j]++;
else
j = i + 1;//进行下一个字符的出现次数记录
}
int max_1=0;
int max_pos;
for (int i = 0; i < 100; i++)
{
if (hash[i] > max_1)
{
max_1 = hash[i];
max_pos = i;
}
}
cout << "max is " << max << '\n'
<< "min is " << min << '\n'
<< "mode is " << s[max_pos] << '\n';
system("PAUSE");
}