• PAT 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 ' '. 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

    出现标点符号的时候, 用空格代替这个标点符号, 否则可能出错
    比如输入字符串为aa'a'a'a' 如果不把标点符号同空格代替, 输出的就是aaaa 1 而不是a 4
    此外, 在字符串的末尾添加一个空格 便于提取最后一个词
     1 #include<iostream>
     2 #include<string>
     3 #include<map>
     4 using namespace std;
     5 int main(){
     6   string s;
     7   int i, cnt=0;
     8   getline(cin, s);//大写字母转小写字母, 标点符号替换为空格
     9   for(i=0; i<s.size(); i++) {
    10     if(s[i]<='Z' && s[i]>='A') s[i] += 32;
    11     else if(!((s[i]>='0' && s[i]<='9') || (s[i]>='a' && s[i]<='z'))) s[i] = ' ';
    12   }
    13   //在末尾添加一个空格, 方便最后一个单词的提取
    14   s.append(" ");
    15   map<string, int> m;
    16   int begin=0, maxn=-1;
    17   string ans="";
    18   for(i=0; i<s.size();){
    19       if(s[i]==' '){//提取每个单词
    20         string temp = s.substr(begin, i-begin);
    21         int num = ++m[temp];
    22         if(maxn<num){
    23             ans = temp;
    24             maxn = num;
    25         }else if(maxn==num && ans>temp) ans=temp;
    26         while(i<s.size() && s[i]==' ') i++;
    27         begin = i;
    28       }
    29       else i++;
    30   }
    31   cout<<ans<<" "<<maxn<<endl;
    32   return 0;
    33 }
    有疑惑或者更好的解决方法的朋友,可以联系我,大家一起探讨。qq:1546431565
  • 相关阅读:
    软件需求变更管理
    Flex自定义事件
    Flex基础控件Button
    Ext JS高级程序设计》即将隆重上市(预计上市时间:091115)
    迈向工程硕士
    Flex基础控件ComboBox
    ExtJS 4 Beta 2预览:Ext.Brew包
    ExtJS 4 Grid组件
    REST WebService与SOAP WebService的比较
    Step by Step WebMatrix网站开发之一:Webmatrix安装
  • 原文地址:https://www.cnblogs.com/mr-stn/p/9231304.html
Copyright © 2020-2023  润新知