其他分享
首页 > 其他分享> > 1071 Speech Patterns (25 分)

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;
}

标签:字符,数字,isalnum,25,检测,字母,是否是,Patterns,Speech
来源: https://blog.csdn.net/q54188p/article/details/114481727