网络运营有前途吗公司seo
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
代码讲解:首先就是数据的输入,题目会输入一句英语(包含大小写),而我们要将句中的单词提取出来,进行统计次数,对题目分析,如A,a,算一个单词,那么就要对单词进行大小写判断,isupper()是判断大小写的函数,大写返回非零的数值(真),小写返回零(假),如果为真将大写转化为小写,使用tolower()函数进行转换,转换之后再用map[word]++,进行次数统计,最后再进行次数排序,打印输出。
代码:
#include <cctype>
#include <iostream>
#include <map>
#include<vector>
#include<algorithm>
using namespace std;int main() {string s;map<string,int> mp;while(getline(cin,s)){for(int i = 0,j = 0;i<s.size();i++){if(s[i]==' '||s[i]=='.'){string t = s.substr(j,i-j);if(isupper(t[0])){t[0] = tolower(t[0]);}j=i+1;mp[t]++;}}auto cmp = [](const pair<string,int>& a,const pair<string,int>& b){return a.second>b.second;};vector<pair<string,int>> v(mp.begin(),mp.end());sort(v.begin(),v.end(),cmp);for(int i = 0;i<v.size();i++){cout<<v[i].first<<":"<<v[i].second<<endl;}}
}
// 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 <= 500
1 <= words[i] <= 10
words[i]
由小写英文字母组成。k
的取值范围是[1, 不同 words[i] 的数量]
这道题,相比于上面的题目就简单了许多,去掉了数据的处理,只需要次数统计与排序。
代码:
class Solution {
public:vector<string> topKFrequent(vector<string>& words, int k) {unordered_map<string,int> cnt;for(auto& word:words){++cnt[word];}vector<string> 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]?a<b:cnt[a]>cnt[b];});rec.erase(rec.begin()+k,rec.end());return rec;}
};