算法提高 ADV-226 笨小猴

问题描述
  笨小猴的词汇量很小,所以每次做英语选择题的时候都很头疼。但是他找到了一种方法,经试验证明,用这种方法去选择选项的时候选对的几率非常大!
  这种方法的具体描述如下:假设maxn是单词中出现次数最多的字母的出现次数,minn是单词中出现次数最少的字母的出现次数,如果maxn-minn是一个质数,那么笨小猴就认为这是个Lucky Word,这样的单词很可能就是正确的答案。
输入格式
  输入文件只有一行,是一个单词,其中只可能出现小写字母,并且长度小于100。
输出格式
  输出文件共两行,第一行是一个字符串,假设输入的的单词是Lucky Word,那么输出“Lucky Word”,否则输出“No Answer”;第二行是一个整数,如果输入单词是Lucky Word,输出maxn-minn的值,否则输出0。
样例输入
error
样例输出
Lucky Word
2
样例说明
  单词error中出现最多的字母r出现了3次,出现次数最少的字母出现了1次,3-1=2,2是质数。
样例输入
olympic
样例输出
No Answer
0
样例说明
  单词olympic中所有字母都只出现了1次,1-1=0,0不是质数。

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

public class Main {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		String words = scanner.nextLine();
		
		words = words.replaceAll(" ", "");
		
		Map<Character, Integer> alphabetCountMap = getCharMaps(words);
		Integer maxReduceMinAlphabetCount = reduceCount(alphabetCountMap);
		
		if(judgePrimeNumber(maxReduceMinAlphabetCount)){
			System.out.println("Lucky Word");
			System.out.println(maxReduceMinAlphabetCount.intValue());
		} else {
			System.out.println("No Answer");
			System.out.println(0);
		}
	}

	public static Map<Character, Integer> getCharMaps(String words){
		 Map<Character, Integer> alphabetCountMap = new HashMap<Character, Integer>();
		 for (int index = 0; index < words.length(); index++) {
			Character alphabet = words.charAt(index);
			Integer count = alphabetCountMap.get(alphabet);
			alphabetCountMap.put(alphabet, count==null ? 1 : count+1);
		}
		 
		 return alphabetCountMap;
	}
	
	private static Integer reduceCount(Map<Character, Integer> alphabetCountMap) {
		Iterator<Entry<Character, Integer>> iterator = alphabetCountMap.entrySet().iterator();
		
		Integer min = Integer.MAX_VALUE;
		Integer max = Integer.MIN_VALUE;
		while (iterator.hasNext()) {
			Entry<Character,Integer> entry = iterator.next();
			if(min.intValue() > entry.getValue().intValue()){
				min = entry.getValue();
			}
			if(max.intValue() < entry.getValue().intValue()){
				max = entry.getValue();
			}
		}
		return max.intValue() - min.intValue();
	}
	
	private static boolean judgePrimeNumber(Integer maxReduceMinAlphabetCount) {
		int maxReduceMinAlphaCountValue = maxReduceMinAlphabetCount.intValue();
		
		if(maxReduceMinAlphaCountValue == 1 || maxReduceMinAlphaCountValue ==  0){
			return false;
		}
		
		for (int i = 2; i < (int)Math.sqrt(maxReduceMinAlphaCountValue)+1; i++) {
			if (maxReduceMinAlphaCountValue % i == 0){
				return false;
			}
		}
		return true;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值