PAT-A 真题 – 1071 Speech Patterns

发布于 / PAT-甲级 / 0 条评论

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

题目大意:词频统计,给一行话,要求找到词频最大的单词。单词由[a-z][A-Z][0-9]组成,标点符号不算单词,单词不区分大小写,最后输出小写单词和出现次数。

这道题使用getline读取句子,然后使用空格/符号进行切词,转小写,使用map<string, int>进行词频统计即可。

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

map<string, int> mp;

bool judge(char &c){  //只保留[a-z][A-Z][0-9],并转小写 
  if(c >= 'A' && c <= 'Z') c += ('a' - 'A');
  return   (c >= '0' && c <= '9') ||
      (c >= 'a' && c <= 'z');
}

void deal(string &s){
  if(s != "") mp[s]++;
  s = "";
}

int main(){
  string input, tmp;
  getline(cin, input);
  for(int i = 0; i < input.length(); i++)
    if(judge(input[i]))
      tmp += input[i];
    else
      deal(tmp);
  if(tmp.size()) deal(tmp);  //防止只有一个单词 
  int M = 0;
  string ans = "";
  for(auto i : mp)
    if(i.second > M){
      ans = i.first;
      M = i.second;
    }else if(i.second == M && i.first < ans)
      ans = i.first;
  cout << ans << ' ' << M << endl;
  return 0;
}

转载原创文章请注明,转载自: 斐斐のBlog » PAT-A 真题 – 1071 Speech Patterns
目前还没有评论,快来抢沙发吧~