1071 Speech Patterns (25分)

非 Y 不嫁゛ 提交于 2020-02-02 00:29:32

1071 Speech Patterns (25分)

People often have a preference among synonyms of the same word. For example, some may prefer “the police”, while others may prefer “the cops”. Analyzing such patterns can help to narrow down a speaker’s identity, which is useful when validating, for example, whether it’s still the same person behind an online avatar.

Now given a paragraph of text sampled from someone’s speech, can you find the person’s most commonly used word?

Input Specification:

Each input file contains one test case. For each case, there is one line of text no more than 1048576 characters in length, terminated by a carriage return \n. The input contains at least one alphanumerical character, i.e., one character from the set [0-9 A-Z a-z].

Output Specification:

For each test case, print in one line the most commonly occurring word in the input text, followed by a space and the number of times it has occurred in the input. If there are more than one such words, print the lexicographically smallest one. The word should be printed in all lower case. Here a “word” is defined as a continuous sequence of alphanumerical characters separated by non-alphanumerical characters or the line beginning/end.

Note that words are case insensitive.

Sample Input:

Can1: “Can a can can a can? It can!”

Sample Output:

can 5

题目大意:

输入一段话, 找出出现频率最大的单词, 其中一个单词只由[0–9, a–z, A–Z]构成

分析:

变量说明: 只用ch变量来保存输入的段落, res是频率最大的单词, word保存每次输入的单词, hp保存由string到int的映射, 即每个单词出现的次数, cnt是频率最大的单词的出现次数
算法思路: 每次输入一个字符, 若该字符是组成单词的字符, 则将其加入到word中, 否则说明一个单词已经输入完毕, 将对应的映射值自增1, 若自增后的值大于结果值, cnt置为该值, 并将res保存为当前的字符串; 最后输出即可

#include <bits/stdc++.h>
using namespace std;
char ch;
string res, word;
unordered_map<string, int> hp;
int cnt = 0;
int main() {
    do {
        ch = getchar();
        if(!isalnum(ch)) {
            hp[word]++;
            if(word.size() > 0 && hp[word] > cnt) {
                cnt = hp[word];
                res = word;
            }
            word = "";
        } else {
            word = word + string(1, tolower(ch));
        }
    }while('\n' != ch);
    cout << res << " " << cnt;
    return 0;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!