PAT 1071

题目 : Speech Patterns

分值 : 25
难度 : 中等题
思路 : 字符串划分,每次从一个合法的字符表示一个一个单词开始,到底一个非法字符,这个单词
       结束,然后去Map里面查询一下,这里一定要对 map<string ,int >做初始化.
坑点 : 每次分词,最后一个单词可能结尾都是合法词汇.需要特殊处理,最取巧的方法就是在最后自
       几加上一个" ",人工设置一个非法词汇帮助分词.

具体代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <iostream>
#include <string>
#include <map>
using namespace std ;
map <string,int> Map ;
map <string,int >::iterator iter ;
void to_lowcase(string &a)
{
for(int i = 0 ; i< a.size() ; i++)
{
if(a[i]>='A' && a[i]<='Z')
{
a[i] = a[i]-'A' +'a';
}
}
}
bool is_alph(char a)
{
if( (a>='0' && a<='9') || (a>='a' && a<='z'))
return true ;
return false ;
}
int main() {
string s;
getline(cin ,s ) ;
to_lowcase(s) ;
//s+=" ";
//cout <<s <<endl ;
string temp ="";
bool flag = false ;
for(int i = 0 ; i< s.size() ; i++)
{
if(!flag)
{
if(is_alph(s[i]))
{
temp +=s[i] ;
flag =true ;
}
}
else
{
if(!is_alph(s[i])) //遇到了不是alph的字母 截断
{
iter =Map.find(temp);
if(iter!=Map.end() )
Map[temp]++ ;
else Map[temp] = 1 ;
//cout << temp<<" " ;
flag =false ;
temp = "" ;
}
else
temp+=s[i] ;
}
}
if(flag)
{
iter = Map.find(temp);
if(iter != Map.end())
Map[temp]++ ;
else Map[temp] =1 ;
}
//cout <<endl ;
int max ;
string result ;
for(iter = Map.begin() ; iter!=Map.end() ;iter++)
{
if( iter->second > max )
{
max = iter->second ;
result = iter->first;
}
else if(iter->second==max && (result >iter->first) )
{
max = iter->second ;
result = iter->first;
}
}
cout << result<<" "<<max <<endl ;
}