数据结构与算法题目集7-46——新浪微博热门话题

版权声明:我的GitHub:https://github.com/617076674。真诚求星! https://blog.csdn.net/qq_41231926/article/details/84928935

我的数据结构与算法题目集代码仓:https://github.com/617076674/Data-structure-and-algorithm-topic-set

原题链接:https://pintia.cn/problem-sets/15/problems/893

题目描述:

知识点:字符串

思路:用map<string, set<int> >型变量belongs记录每个热词对应的话题数量

值采用set集合的目的是去除,防止一个话题中有多个相同的热词。

读入过程中,将大写字母转变为小写字母,将字母或数字或空格加入字符串中,而对于其他字符,如果其下一个字符存在,且下一个字符是字母或数字,就需要将其替换为空格,否则,我们忽略之

得到最热门的词之后,输出该词时需要去掉前导空格、后导空格以及单词之间的多余空格

时间复杂度和空间复杂度均与录入的字符串总长度有关。

C++代码:

#include<iostream>
#include<string>
#include<cstring>
#include<map>
#include<set>

using namespace std;

int N;
map<string, set<int> > belongs;

int main() {
	scanf("%d", &N);
	getchar();
	for(int i = 0; i < N; i++) {
		char input[141];
		scanf("%[^\n]", input);
		getchar();
		string str = "";
		int flag = 0;
		for(int j = 0; j < strlen(input); j++) {
			if(input[j] == '#') {
				flag++;
				if(flag == 2) {
					flag = 0;
					if(str.length() != 0) {
						belongs[str].insert(i);
					}
					str = "";
				}
				continue;
			}
			if(flag == 1) {
				if(input[j] >= 'A' && input[j] <= 'Z') {	//将大写字母转变成小写字母 
					input[j] = input[j] - 'A' + 'a';
				}
				if((input[j] >= 'a' && input[j] <= 'z') || 
					(input[j] >= '0' && input[j] <= '9') || input[j] == ' ') {	 //如果是字母或数字或空格,就加入字符串中 
					str += input[j];
				}else if(j + 1 < strlen(input) && ((input[j + 1] >= 'a' && input[j + 1] <= 'z') || 
					(input[j + 1] >= 'A' && input[j + 1] <= 'Z') || (input[j + 1] >= '0' && input[j + 1] <= '9'))){	
					//如果下一个字符是字母或数字且下一个字符不超出input的长度范围,则将其替换为空格 
					str += ' ';
				}
			}
		}
	}
	int maxTimes = 0;	//记录最热门的词出现话题数量 
	string tempResult;	//记录最热门的词 
	for(map<string, set<int> >::iterator it = belongs.begin(); it != belongs.end(); it++) {
		if(it->second.size() > maxTimes) {
			tempResult = it->first;
			maxTimes = it->second.size();
		}
	}
	int other = 0;	//计算与最热门词对应话题数量有着相同数量的话题总数 
	for(map<string, set<int> >::iterator it = belongs.begin(); it != belongs.end(); it++) {
		if(it->second.size() == maxTimes) {
			other++;
		}
	}
	string result = "";
	while(tempResult.length() > 0 && tempResult[0] == ' '){	//去除前导空格 
		tempResult.erase(tempResult.begin());
	}
	while(tempResult.length() > 0 && tempResult[tempResult.length() - 1] == ' '){	//去除后导空格 
		tempResult.erase(tempResult.end());
	}
	for(int i = 0; i < tempResult.length(); i++) {	//去除单词之间多余的空格 
		if(i > 0 && tempResult[i - 1] == ' ' && tempResult[i] == ' ') {
			continue;
		}
		result += tempResult[i];
	}
	int count = belongs[result].size();	
	if(result[0] >= 'a' && result[0] <= 'z') {
		result[0] = result[0] - 'a' + 'A';
	}
	printf("%s\n%d\n", result.c_str(), count);
	if(other > 1) {
		printf("And %d more ...\n", other - 1);
	}
	return 0;
}

C++解题报告:

猜你喜欢

转载自blog.csdn.net/qq_41231926/article/details/84928935