Pat(A) 1071. Speech Patterns (25)

来源:互联网 发布:汤姆大叔 javascript 编辑:程序博客网 时间:2024/06/05 14:14

原题目:

原题链接:https://www.patest.cn/contests/pat-a-practise/1071

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

解题报告

题目大意是找出句中出现次数最多的单词,并输出。
需要注意的是:
1. 末尾有可能存在可行字符(切记切记)。
1. 字母的大小写。

解决方案就是遍历字符,是合法则计入,不是则添加上一合法字符,最后记得处理最后一个字符是可行字符的情况。

代码

#include "iostream"#include "algorithm"#include "map"#include "vector"#include "string"using namespace std;char isAlpha(char c){    if(c<='9' && c >= '0')        return c;    if(c<='z' && c >= 'a')        return c;    if(c<='Z' && c >= 'A')        return c-('A' - 'a');    return 0;} bool comp(const pair<string,int> &a,const pair<string,int> &b){    return a.second>b.second;}int main(){    map<string,int> mm;    map<string,int>::iterator it;    char c;    string s = "";    while(scanf("%c",&c)){        if(c=='\n')            break;        c = isAlpha(c);        if (c)            s += c;        else{            if(s.size()){                if(mm.count(s)){                    mm[s] ++;                }else{                    mm[s] = 1;                }            }            s = "";        }    }    // 处理如果最后是可行字符的情况    if(s.size()){        if(mm.count(s)){            mm[s] ++;        }else{            mm[s] = 1;        }    }    vector<pair<string,int>> v(mm.begin(),mm.end());    sort(v.begin(),v.end(),comp);    cout<<v[0].first<<" "<<v[0].second<<endl;    //system("pause");}
原创粉丝点击