杭电oj-1004(Let the Balloon Rise)

Problem Description

Contest time again! How excited it is to see balloons floating around. But 
to tell you a secret, the judges' favorite time is guessing the most popular 
problem. When the contest is over, they will count the balloons of each 
color and find the result.

This year, they decide to leave this lovely job to you. 

Input

Input contains multiple test cases. Each test case starts with a number N (0 
< N <= 1000) -- the total number of balloons distributed. The next N lines 
contain one color each. The color of a balloon is a string of up to 15 
lower-case letters.

A test case with N = 0 terminates the input and this test case is not to be 
processed.

Output

For each case, print the color of balloon for the most popular problem on a 
single line. It is guaranteed that there is a unique solution for each test 
case.

Sample Input

5
green
red
blue
red
red
3
pink
orange
pink
0

Sample Output

red
pink

Author

WU, Jiazhi

刚开始读这道题的时候,真的有点读乱啦,然后就各种翻译,后来才明白什么意思~其实就是说,我们会输入一堆字符串,让我们调出来里面出现次数最多的那个字符串。这道题我采用的是键值对的方式,当然在java里面我们有现成的方式实现它那就是hashMap,当然在很多其它的语言中,大家都亲切的称他为字典,原理是一样的,我就是遇到一个数,就看看字典里面有没有,如果有那就把这个键对应的值加一再放回去,如果没有那就把这个值当做键,把数字1当做值放进去,最后遍历一下我们的字典,找出值最大的那个,记下值最大的数的键,最终输出这个键就好了。

代码:


import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;

import java.util.Scanner;

public class Main1004 {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        List list = new ArrayList<>();
        while (true) {
            Map aMap = new HashMap<>();
            int T = in.nextInt();
            if (T != 0) {
                int m = T;
                while (T > 0) {
                    String bString = in.next();
                    if (aMap.get(bString) == null) {
                        aMap.put(bString, 1);
                    } else {
                        int count = aMap.get(bString);
                        aMap.remove(bString);
                        count++;
                        aMap.put(bString, count);
                    }
                    T--;
                }
                int i = 0;
                String result = null;
                for (String key : aMap.keySet()) {
                    int a = aMap.get(key);
                    if (a > i) {
                        i = a;
                        result = key;
                    }
                }
                list.add(result);
            } else {
                for (int i = 0; i < list.size(); i++) {
                    System.out.println(list.get(i));
                }

                return;
            }

        }

    }
}

你可能感兴趣的:(杭电oj-1004(Let the Balloon Rise))