1071 Speech Patterns

Posted kkmjy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1071 Speech Patterns相关的知识,希望对你有一定的参考价值。

题意:给出一个字符串,找出词频最高的单词和相应的词频。(这个就是我之前做的一个项目的一个函数啊,哈哈哈)

思路:利用map定义字典map<string,int> dict。主要是字符串的截取,这里用上了几个比较方便的函数,总结如下:

几个有助于节省编码时间的字符串处理函数(在头文件<ctype.h>或<cctype>下)

  • isalnum 判断字符是否为字母(含大小写)或数字
  • isalpha 判断字符是否为字母(含大小写)
  • islower 判断字符是否为小写字母
  • isupper 判断字符是否为大写字母
  • isdigit 判断字符是否为数字
  • tolower 把大写字母转换成小写字母
  • toupper 把小写字母转换成大写字母

代码:

#include <iostream>
#include <cctype>//isalnum(),tolower()
#include <string>
#include <map>
#include <fstream>
using namespace std;
int main()
{
    //ifstream cin("pat.txt");
    string str;
    getline(cin,str);
    int len=str.size();
    for(int i=0;i<len;i++)
        str[i]=tolower(str[i]);
    map<string,int> dict;//定义字典
    int low=0;
    while(low<len){
        int i=low;
        while(i<len && isalnum(str[i])) i++;
        if(i>low){
            string word=str.substr(low,i-low);
//            if(dict.find(word)==dict.end())//这几句写不写都没关系
//                dict.insert(make_pair(word,1));
//            else
            dict[word]++;
        }
        low=i+1;
    }
    string ans;
    int maxFreq=0;
    for(auto it:dict){
        if(it.second>maxFreq){
            ans=it.first;
            maxFreq=it.second;
        }
    }
    cout<<ans<< <<maxFreq;
    return 0;
}

 

以上是关于1071 Speech Patterns的主要内容,如果未能解决你的问题,请参考以下文章