怎么做垂直网站,做电影网站怎么降低内存,有账号和密码怎么进公司网站后台,wordpress自动标签链接KY264 单词识别
题目描述#xff1a;
输入一个英文句子#xff0c;把句子中的单词(不区分大小写)按出现次数按从多到少把单词和次数在屏幕上输出来#xff0c;次数一样的按照单词小写的字典序排序输出#xff0c;要求能识别英文单词和句号。
输入描述#xff1a;
输入…KY264 单词识别
题目描述
输入一个英文句子把句子中的单词(不区分大小写)按出现次数按从多到少把单词和次数在屏幕上输出来次数一样的按照单词小写的字典序排序输出要求能识别英文单词和句号。
输入描述
输入为一行由若干个单词和句号组成
输出描述
输出格式参见样例。
示例1
输入
A blockhouse is a small castle that has four openings through which to shoot.
复制输出
a:2
blockhouse:1
castle:1
four:1
has:1
is:1
openings:1
shoot:1
small:1
that:1
through:1
to:1
which:1
代码讲解首先就是数据的输入题目会输入一句英语包含大小写而我们要将句中的单词提取出来进行统计次数对题目分析如Aa算一个单词那么就要对单词进行大小写判断isupper()是判断大小写的函数大写返回非零的数值(真)小写返回零假如果为真将大写转化为小写使用tolower()函数进行转换转换之后再用map[word],进行次数统计最后再进行次数排序打印输出。
代码
#include cctype
#include iostream
#include map
#includevector
#includealgorithm
using namespace std;int main() {string s;mapstring,int mp;while(getline(cin,s)){for(int i 0,j 0;is.size();i){if(s[i] ||s[i].){string t s.substr(j,i-j);if(isupper(t[0])){t[0] tolower(t[0]);}ji1;mp[t];}}auto cmp [](const pairstring,int a,const pairstring,int b){return a.secondb.second;};vectorpairstring,int v(mp.begin(),mp.end());sort(v.begin(),v.end(),cmp);for(int i 0;iv.size();i){coutv[i].first:v[i].secondendl;}}
}
// 64 位输出请用 printf(%lld)
692. 前K个高频单词
给定一个单词列表 words 和一个整数 k 返回前 k 个出现次数最多的单词。
返回的答案应该按单词出现频率由高到低排序。如果不同的单词有相同出现频率 按字典顺序 排序。 示例 1
输入: words [i, love, leetcode, i, love, coding], k 2
输出: [i, love]
解析: i 和 love 为出现次数最多的两个单词均为2次。注意按字母顺序 i 在 love 之前。示例 2
输入: [the, day, is, sunny, the, the, the, sunny, is, is], k 4
输出: [the, is, sunny, day]
解析: the, is, sunny 和 day 是出现次数最多的四个单词出现次数依次为 4, 3, 2 和 1 次。注意
1 words.length 5001 words[i] 10words[i] 由小写英文字母组成。k 的取值范围是 [1, 不同 words[i] 的数量]
这道题相比于上面的题目就简单了许多去掉了数据的处理只需要次数统计与排序。
代码
class Solution {
public:vectorstring topKFrequent(vectorstring words, int k) {unordered_mapstring,int cnt;for(auto word:words){cnt[word];}vectorstring rec;for(auto [key,value]:cnt){rec.emplace_back(key);}sort(rec.begin(),rec.end(),[](const string a,const string b)-bool{return cnt[a]cnt[b]?ab:cnt[a]cnt[b];});rec.erase(rec.begin()k,rec.end());return rec;}
};