要求:单词大小小于1000,当次数重复时,按字母表大小排序(a在b前)
做了个中间容器vec,没那么暴力的算法
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
int max = 0, m_max = 0;//定义最大值,后面比较要用
int index = 0;//最大值的位置
bool flag = false;
string eng_word;//用来存单词
string vec;//用来提取单词中独立的元素,比如aaabb,vec中就只有ab
int arr[1000] = { 0 };//用来记录每个单词出现了几次
vector<int> str;//用来判断字母表顺序的数组
do
{
cin >> eng_word;
} while ((eng_word.size() >= 1000));//当大于1000时重新输出
for (int i = 0; i < eng_word.size(); i++)//vec得到数据的操作
{
if (vec.empty())
{
vec.push_back(eng_word[i]);
}
else
{
flag = true;
for (int j = 0; j < vec.size(); j++)
{
if (eng_word[i] == vec[j])
{
flag = false;
arr[j]++;
}
}
if (flag)
{
vec.push_back(eng_word[i]);
}
}
}
for (int i = 0; i < vec.size(); i++)//得到出现次数最多次的字母,作为最大值
{
if (max == 0)
{
max = arr[i];
}
if (arr[i] <= arr[i + 1] && i < vec.size() - 1 && arr[i + 1] >= max)
{
max = arr[i + 1];
index = i + 1;
}
}
for (int i = 0; i < vec.size(); i++)//因为有多个字母有相同的最大值,所以要进一步筛选
{
if (arr[i] == max)
{
str.push_back(i);
}
}
if (str.size() != 1)//筛选过程和上面差不多,筛多一遍
{
for (int i = 0; i < str.size(); i++)
{
if (m_max == 0)
{
m_max = vec[str[i]];
index = str[i];
}
else if (vec[str[i]] < m_max)
{
m_max = vec[str[i]];
index = str[i];
}
}
}
else if (str.size() == 1)
{
index = str[0];
}
cout << vec[index] << endl;//最终输出
cout << max + 1 << endl;
return 0;
}
水平不足,多多指教
估计过一年后再来看自己的代码会很羞耻把XD