PAT A1071 Speech Patterns (25分)

题目描述

在这里插入图片描述

知识点

哈希

我的实现

码前思考

按照题目的定义,并不是仅仅以空格为分隔符分割单词的,其他只要不是数字或者字母的字符都可以作为分割符!!!

所以我们选择一个个字符的读取,只要读到一个非字母或者数字时,就代表生成了一个单词(前提是这个单词是非空的!)

代码实现

#include<stdio.h>
#include<map>
#include<string>
#include<iostream>
using namespace std;

bool isAOrN(char a){
	if(a>='0' && a<='9' || a>='A' && a<='Z' || a>='a' && a<='z'){
		return true;
	}else{
		return false;
	}
}


int main(){
	map<string,int> cnt;
	
	string input;
	//要输入整行的字符使用cin 
	getline(cin,input);

	int idx=0;
	
	string maxKey;
	int maxNum=0;
	
	while(idx < input.length()){
		string word;
		while(isAOrN(input[idx])){
			if(input[idx] >='A' && input[idx] <= 'Z'){
				word += (input[idx] - 'A' + 'a');	
			}else{
				word += input[idx];				
			}
			idx++;
		}
		if(!word.empty()){
			if(cnt.find(word) != cnt.end()){
				cnt[word]++;
			}else{
				cnt[word]=1;
			}
			if(cnt[word]>maxNum || cnt[word] == maxNum && word<maxKey){
				maxKey = word;
				maxNum = cnt[word];
			}			
		}
		idx++;
	}
	
	cout<<maxKey<<" "<<maxNum;
	return 0;
}

码后反思

这里使用的是自己写的函数判断字符和转换字符,其实也可以用库里的函数:toupper()、tolower()、isalnum();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值