您的位置:首页 > 其它

算法提高 ADV-132 笨小猴

2017-08-26 00:40 399 查看
问题描述

  笨小猴的词汇量很小,所以每次做英语选择题的时候都很头疼。但是他找到了一种方法,经试验证明,用这种方法去选择选项的时候选对的几率非常大!

  这种方法的具体描述如下:假设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;
}
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: