一、題目描述
原題鏈接

Input Specification:

??Output Specification:

Sample Input:
Can1: “Can a can can a can? It can!”
Sample Output:
can 5
二、解題思路
要找出一句話中最常出現的單詞以及出現次數,要求不區分大小寫,因為輸出要求是小寫,所以我們可以寫一個將字串轉換成小寫的函式to_lower(string str),建立一個字串到int型的map,表示單詞出現的個數,我們知道,一個單詞是連續的,且只包含字母(題目把數字也算上了),所以我們可以遍歷題目給的字串,將每個連續的單詞對應的mp加1,同時更新出現最多的單詞以及對應次數,遍歷完之后進行輸出即可,
三、AC代碼
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<unordered_map>
#include<map>
#include<cctype>
using namespace std;
map<string, int> mp;
string to_lower(string str)
{
string ans = str;
for(int i=0; i<ans.size(); i++)
{
if(ans[i] >= 'A' && ans[i] <= 'Z') ans[i] = 'a' - 'A' + ans[i];
}
return ans;
}
int main()
{
string str, ans;
int maxn = 0;
getline(cin, str);
for(int i=0; i<str.size(); )
{
string tmp = "";
while(i<str.size() && ((str[i]<='Z' && str[i]>='A') || (str[i]<='z' && str[i]>='a') || (str[i]>='0' && str[i]<='9')))
{
tmp += str[i];
i++;
}
if(tmp != "")
{
mp[to_lower(tmp)]++;
if(mp[to_lower(tmp)] > maxn)
{
maxn = mp[to_lower(tmp)];
ans = to_lower(tmp);
}
}
i++;
}
printf("%s %d", ans.c_str(), maxn);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/116600.html
標籤:其他
