1 #include<iostream> 2 #include<string> 3 #include<map> 4 using namespace std; 5 bool check(char c) { // 检查字符是否是 [0-9 A-Z a-z]. 6 if(c >= '0' && c <= '9') return true; 7 if(c >= 'A' && c <= 'Z') return true; 8 if(c >= 'a' && c <= 'z') return true; 9 return false; 10 } 11 int main() { 12 map<string, int> count; // count计数字符串出现的次数 13 string str; 14 getline(cin, str); // 读入整行字符串 15 int i = 0; // 定义下标 16 while(i < str.length()) { // 在字符串范围内 17 string word; // 单词 18 while(i < str.length() && check(str[i]) == true) { // 如果是单词的字符 19 if(str[i] >= 'A' && str[i] <= 'Z') { 20 str[i] += 32; // 大写字母转小写 21 } 22 word += str[i]; // 单词末尾添加该字符 23 i++; // 下标后移一位 24 } 25 if(word != "") { // 单词非空,令次数加一 26 if(count.find(word) == count.end()) 27 count[word] = 1; 28 else 29 count[word]++; 30 } 31 while(i < str.length() && check(str[i]) == false) { 32 i++; // 跳过非单词字符 33 } 34 } 35 string ans; // 存放出现次数最多的单词 36 int MAX = 0; // 出现最多的单词的次数 37 for(map<string, int>::iterator it = count.begin(); it != count.end(); it++) { 38 if(it->second > MAX) { // 寻找出现次数最多的单词 39 MAX = it->second; 40 ans = it->first; 41 } 42 } 43 cout << ans << " " << MAX << endl; // 输出结果 44 return 0; 45 }
PAT 甲级 A1071 (2019/02/23)
猜你喜欢
转载自www.cnblogs.com/zjsaipplp/p/10422755.html
今日推荐
周排行