PTA:7-120 新浪微博热门话题 (30分)--(map方法,加解析)

7-120 新浪微博热门话题 (30分)

新浪微博可以在发言中嵌入“话题”,即将发言中的话题文字写在一对“#”之间,就可以生成话题链接,点击链接可以看到有多少人在跟自己讨论相同或者相似的话题。新浪微博还会随时更新热门话题列表,并将最热门的话题放在醒目的位置推荐大家关注。

本题目要求实现一个简化的热门话题推荐功能,从大量英文(因为中文分词处理比较麻烦)微博中解析出话题,找出被最多条微博提到的话题。
在这里插入图片描述
输入样例:
4
This is a #test of topic#.
Another #Test of topic.#
This is a #Hot# #Hot# topic
Another #hot!# #Hot# topic

输出样例:
Hot
2
And 1 more …

思路:
核心思路采用map进行标记,如map[“hello”]++;
利用map直接可以统计字符串出现的次数,解决该类型题目,比较方便。
map用好了,剩下的就是处理一些细节问题,这个个人认为一次通过全部测试点还是比较困难的。
下面是从别的大佬博客参考到的测试样例(ps:我开始就是两个测试点没通过,最后改进代码通过了下面几个样例,就全通过了,嘻嘻,向大佬学习)
原文链接:https://blog.csdn.net/henuni/article/details/75907043
补充测试样例:
补充样例1:
输入:
4
This is a #test of 1 topic#.
Another #Test of (1)topic.#
This is a #Hot# topic
This is a test of 1 topic
输出:
Test of 1 topic
2

补充样例2:
输入:
3
Test #for@ diff words#
Test #ford iff words#
#more than# one #topics.#
输出:
For diff words
1
And 3 more…

具体代码解析见AC代码:

#include<bits/stdc++.h>
using namespace std;
map<string, int> mp;   
string ans;

int main(){
	int n,i;
	string s;
	cin>>n;
	getchar(); //不能再循环里,否则可能第一个字符就被吃了 
	while(n--){
		getline(cin,s);
		map<string, int> mp2;
		i=0;
		while(i<s.size()){
			string str="";
			for(;i<s.size(); i++){
				if(s[i]=='#'){
					i++;
					break;
				} 
			}
			//对字符串预处理,即去掉不是英文和数字的字符 
			int j=i;
			for(;s[j]&&s[j]!='#'; j++){
				if(!isalpha(s[j])&&!isdigit(s[j])){
					s[j]=' ';
				}
			}
			for(;s[i]&&s[i]!='#'; i++){
				if(isalpha(s[i])||isdigit(s[i])){
					str+=tolower(s[i]);
				}else if(str!=""&&s[i]==' '&&(isalpha(s[i+1])||isdigit(s[i+1]))){
					str+=' '; 
				}
			}
			i++;
			if(str!=""&&!mp2[str]){  //这里mp2判断str话题是否已经存在了,不存在的话再统计mp中 
			//	cout<<"str:"<<str<<endl;
				mp2[str]++;
				mp[str]++;	
			}  
		}
	}
	int maxx=-1,cnt=0,maxnum;
	map<string,int>::iterator it;
	for(it=mp.begin(); it!=mp.end(); it++){  //找到热门话题出现次数 
		if(it->second>maxx) maxx=it->second;
	}
	for(it=mp.begin(); it!=mp.end(); it++){ //利用map自动排序性质,输出第一个最大热门话题,统计最大热门话题次数 
		if(it->second==maxx){
			if(cnt==0){
				ans=it->first;	
				maxnum=it->second;
			}	
			cnt++;
		} 
	}
	for(int i=0; i<ans.size(); i++){
		if(i==0){
			char ch=toupper(ans[i]);  //将首字符变为大写输出 
			cout<<ch;	
		} 
		else cout<<ans[i];
	}
	cout<<endl<<maxnum<<endl;
	if(cnt>1) cout<<"And "<<cnt-1<<" more ..."<<endl;
	return 0;
} 

在这里插入图片描述
欢迎大家批评改正!!!

发布了49 篇原创文章 · 获赞 2 · 访问量 3910

猜你喜欢

转载自blog.csdn.net/weixin_43581819/article/details/104102928