POJ1002 487-3279

这个题目主要是涉及进行电话号码的转换,使用TreeMap来对电话号码进行统计以及排序。

 

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


public class Main {
    private static Map<Character,Character> map = new HashMap<Character, Character>();
    static {
        map.put('A','2');
        map.put('B','2');
        map.put('C','2');
        map.put('D','3');
        map.put('E','3');
        map.put('F','3');
        map.put('G','4');
        map.put('H','4');
        map.put('I','4');
        map.put('J','5');
        map.put('K','5');
        map.put('L','5');
        map.put('M','6');
        map.put('N','6');
        map.put('O','6');
        map.put('P','7');
        map.put('R','7');
        map.put('S','7');
        map.put('T','8');
        map.put('U','8');
        map.put('V','8');
        map.put('W','9');
        map.put('X','9');
        map.put('Y','9');
    }
    public static void main(String args[]) throws Exception
    {
        Scanner cin=new Scanner(System.in);
        int count = cin.nextInt();
        cin.nextLine();
        Map<String,Integer> phoneToCountMap = new TreeMap<String, Integer>();
        for(int idx = 0;idx < count;idx++){
            String rawPhone = cin.nextLine();
            String standardPhone = convertToStandardPhone(rawPhone);
            int phoneCount = 0;
            if(phoneToCountMap.containsKey(standardPhone)){
                phoneCount = phoneToCountMap.get(standardPhone);
            }
            phoneCount++;
            phoneToCountMap.put(standardPhone,phoneCount);
        }


        int dupCount = 0;
        for (Map.Entry<String, Integer> stringIntegerEntry : phoneToCountMap.entrySet()) {
            int phoneCount = stringIntegerEntry.getValue();
            if(phoneCount > 1){
                dupCount++;
                System.out.println(stringIntegerEntry.getKey()+" "+stringIntegerEntry.getValue());
            }
        }

        if(dupCount == 0){
            System.out.println("No duplicates.");
        }

    }

    
    private static String convertToStandardPhone(String rawPhone){
        char[] charArray = rawPhone.toCharArray();
        StringBuilder builder = new StringBuilder("");
        for (char c:charArray){
            if(c == '-'){
                continue;
            }
            if(map.containsKey(c)){
                c = map.get(c);
            }
            if(builder.length() == 3){
                builder.append('-');
            }
            builder.append(c);
        }
        return builder.toString();
    }
}
 

你可能感兴趣的:(poj)