java 复习之字符串处理

版权声明:本文章由BlackCarDriver原创,欢迎评论和转载 https://blog.csdn.net/BlackCarDriver/article/details/89133620

本代主要用来复习java常用的字符串操作方法和HashMap的基本使用。

题目要求:
给出一行带空格和符号的英文语句,你需要从中找出出现频率最多的单词,若有多个单词频率相同则输出字典序最小的一个。注意单词是又数字或大小写字母组成的长度最小为一的片段,对大小写不敏感。
分析:
需要用到字符串的分割,以及hashmap的简单使用。java的优势是提供了比c++跟多跟灵活的字符串操作函数,缺点是相对于c++,hashmap的使用略显臃肿。不过最终代码java比c++简短不少。
知识点
string使用正则表达式分割
HashMap的插入,遍历,取值

MyCode

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scn = new Scanner(System.in);
		String[] word = scn.nextLine().toLowerCase().split("[^a-zA-Z0-9]+");
		Map<String, Integer> simap = new HashMap<String, Integer>();
		Integer maxnum = 0;
		for (String temp : word) {
			Integer count = simap.get(temp);
			count = count==null? 1:count+1;
			simap.put(temp, count);
			maxnum = count > maxnum ? count : maxnum;
		}
		//投机取巧,其实是破绽
		String ans = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz";
		for (Entry<String, Integer> p : simap.entrySet()) {
			if (p.getValue() == maxnum) {
				ans = ans.compareTo(p.getKey())<0?ans:p.getKey();
			}
		}
		System.out.println(ans+" "+maxnum);
	}
}

回顾
java的hashmap 取值时,若键值不存在,value为 null 而不是0,第一次写时因此出现了报错。另外注意HashMap的插入只能用push,不可以直接++…
坑点:在遍历hashmap取出频率最大的单词时,想不到按照取出第一个value=maxunm 的方法作为答案的方法行不通。这里是跟c++ map 不同的一个地方。最后全部取出,依次比较,通过。

猜你喜欢

转载自blog.csdn.net/BlackCarDriver/article/details/89133620