PAT A1071

题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805398257647616

第三个测试用例错误。我怀疑我这种算法是无法判断 “beginning/end”这种情况。

#include <cstdio>
#include <iostream>
#include <map>
#include <string>
using namespace std;
map<string, int> count;
string change(string a){
	for(int i = 0; i < a.length(); i++){
		if(a[i] >= 'A' && a[i] <= 'Z'){
			char b = a[i] - 'A' + 'a';
			a.erase(a.begin() + i);
			a.insert(a.begin() + i, b);
		}
		else if(!(a[i] >= 'a' && a[i] <= 'z') && !(a[i] >= '0' && a[i] <= '9')){
			a.erase(a.begin()+i);
			i--;
		}
	}
	return a;
}
int main(){
	string str;
 	while(1){
		cin>>str;
		str = change(str);
		if(str.length() > 0){
			if(count.find(str) != count.end()){
				count[str]++;
			}
			else
				count[str] = 1;
		}
		if(getchar() == '\n')
			break;
	}
	string word;
	int times = -1;
	for(map<string, int>::iterator it = count.begin(); it != count.end(); it++){
		if(times < it->second){
			word = it->first;
			times = it->second;
		}
		else if(times == it->second){
			if(word > it->first){
				word = it->first;
			}
		}
	}
	cout<<word<<" "<<times<<endl;
	return 0;
}

参考算法笔记的思路,重新写了一种算法:

#include <cstdio>
#include <iostream>
#include <map>
#include <string>
using namespace std;
map<string, int> count;
bool judge(char& a){
	if(a >= 'a' && a <= 'z')
		return true;
	else if(a >= 'A' && a <= 'Z'){
		a = a - 'A' + 'a';
		return true;
	}
	else if(a >= '0' && a <= '9')
		return true;
	else
		return false;
}

int main(){
	string str;
	getline(cin, str);
	for(int i = 0; i < str.length(); i++){
		while(i < str.length() && !judge(str[i]))
			i++;
		string word;
		while(i < str.length() && judge(str[i])){
			word += str[i];
			i++;
		}
		if(word.length() > 0){
			if(count.find(word) != count.end())
				count[word]++;
			else
				count[word] = 1;
		}
	}
	string word;
	int times = -1;
	for(map<string, int>::iterator it = count.begin(); it != count.end(); it++){
		if(times < it->second){
			word = it->first;
			times = it->second;
		}
		else if(times == it->second){
			if(word > it->first){
				word = it->first;
			}
		}
	}
	cout<<word<<" "<<times<<endl;
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值