程序设计基础70 STL之扫描长字符串问题

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

一,关注点

1,这道题我本来想着去对这个长字符串整体处理,即把里面的大写全部化为小写,并且把无关符号全部化为空格,结果发现单独摘出单词十分复杂。

2,最后的方法是步步演进,一个字符一个字符往前推进,步步为营而不是整体规划,这种思想同A1060

二,我的没写出来的代码

#include<iostream>
#include<string>
#include<map>
using namespace std;
map<string, int> mapping;
void init(string &str) {
	int len = str.length();
	for (int i = 0; i < len; i++) {
		if (str[i] >= 'A'&&str[i] <= 'Z') {
			str[i] = str[i] + 'a' - 'A';
		}
		else if (!((str[i] >= 'a'&&str[i] <= 'z') || (str[i] >= '0'&&str[i] <= '9'))) {
			str[i] = ' ';
		}
	}
}
int main() {
	int pos = 0;
	int len = 0;
	string str;
	string single;
	getline(cin, str);
	init(str);
	len = str.length();
	
	return 0;
}

三,正确代码

#include<iostream>
#include<string>
#include<map>
using namespace std;
map<string, int> mapping;
bool check(char a) {
	if (a >= '0'&&a <= '9')return true;
	else if (a >= 'a'&&a <= 'z')return true;
	else if (a >= 'A'&&a <= 'Z')return true;
	else return false;
}
int main() {
	int i = 0;
	string str;
	getline(cin, str);
	while (i < str.length()) {
		string word;
		while (check(str[i]) == true&&i < str.length()) {
			if (str[i] >= 'A'&&str[i] <= 'Z') {
				str[i] = str[i] + 'a' - 'A';
			}
			word += str[i];
			i++;
		}
		if (word != "") {
			if (mapping.find(word) == mapping.end())mapping[word] = 1;
			else mapping[word]++;
		}
		while (check(str[i]) == false &&i < str.length()) {
			i++;
		}
	}
	string ans;
	int MAX = 0;
	for (map<string, int>::iterator it = mapping.begin(); it != mapping.end(); it++) {
		if (it->second > MAX) {
			ans = it->first;
			MAX = it->second;
		}
	}
	cout << ans << " " << MAX << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq2285580599/article/details/84654632