PAT:1071. Speech Patterns (25) AC

#include<ctype.h>
#include<iostream>
#include<map>
#include<string>
using namespace std;

bool check(char a)          //判断是否为有效字符
{
  if(isdigit(a) || isalpha(a))
    return true;
  return false;
}
int main()
{
  map<string,int> count;    //单词与次数的映射
  string str;
  getline(cin,str);      //【skill】输入一行,不能用gets
  int i=0;
  while(i<str.length())    //【caution】这里不是size
  {
    while(i<str.length() && check(str[i])==false)    //忽略非有效字符
      ++i;
    string word;
    while(i<str.length() && check(str[i])==true)    //抠出单词
    {
      if(str[i]>='A' && str[i]<='Z')
        str[i]=str[i]-'A'+'a';            //【caution】统计单词,大写要换成小写
      word+=str[i++];
    }
    if(count.find(word)!=count.end())          //统计词频
      ++count[word];
    else
      count[word]=1;
  }
  string ans;
  int MAXtimes=-1;
  for(map<string,int>::iterator it=count.begin() ; it!=count.end() ; ++it)
  {
    if(it->second>MAXtimes)
    {
      MAXtimes=it->second;
      ans=it->first;
    }
  }
  cout<<ans<<" "<<MAXtimes<<endl;
  return 0;
}
posted on 2015-03-10 23:33  Evence  阅读(183)  评论(0编辑  收藏  举报