打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
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 '\n'. 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

思路

本题主要是比较每个单词出现的次数,值得注意就是单词的格式,要去去除大写,变换成小写,数字不变。
从第零个字符开始遍历,首先判断这个字符是否属于大小写字母或者数字,如果是则先变换成小写,将其存入一个新的字符串。当遇到非字母或者数字,或者到达主串的末尾,相当于一个单词拼接完成。然后存入map,重新开始下一个单词的拼接。最后遍历,找到最大值即可。

注意

  1. 大小写不区分,所以统计之前要先s[i] = tolower(s[i]);

  2. [0-9 A-Z a-z]可以简写为cctype头文件里面的一个函数isalnum()
    isalnum() 函数用来检测一个字符是否是字母或者十进制数字。
    如果仅仅检测一个字符是否是字母,可以使用 isalpha() 函数;如果仅仅检测一个字符是否是十进制数字,可以使用 isdigit() 函数。
    如果一个字符被 isalpha() 或者 isdigit() 检测后返回“真”,那么它被 isalnum() 检测后也一定会返回“真”。

  3. 必须用getline读入一长串的带空格的字符串

  4. 先判空,然后再将t 存入map

  5. 最重要的是,如果i已经到了最后一位,不管当前位是不是字母数字,都得将当前这个t放到map里面(只要t长度不为0)

代码

#include<bits/stdc  .h>
#include<iostream>
using namespace std;
map<string,int> m;
int main() {
string s,t;
getline(cin,s);
int len = s.length() ;
for(int i = 0; i<len; i  ) {
//isalnum() 函数用来检测一个字符是否是字母或者十进制数字。
//检测一个字符是否是字母,可以使用 isalpha() 函数;
//如果仅仅检测一个字符是否是十进制数字,可以使用 isdigit() 函数。
if(isalnum(s[i])) { // 检测是否是字母或者数字
s[i] = tolower(s[i]);
t  = s[i];
}
if(!isalnum(s[i])||i == len -1  ) { //不是字母数字 或者到达最后
if(t.length() != 0)
m[t]   ; //个数 1
t = "";//更新置空
}

}
int maxn = 0;
for(auto it = m.begin(); it != m.end(); it   ) {
if(it->second>maxn) {
maxn = it->second;
t = it->first;
}
}
cout<<t<<" "<<maxn;
}
来源:https://www.icode9.com/content-4-881801.html
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Python 字符串总结,建议收藏!
C语言学习教程第三章-C语言程序设计初步(3)
C++-十进制转二进制(matlab-dec2bin函数)
C语言字符检测函数:isalnum、isalpha、isascii、iscntrl、isdigit、isgraph、islower、isspace、ispunct、isupper......
ctype.h
Python基础知识自学整理1
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服