题解 | [Java] #记票统计#

记票统计

http://www.nowcoder.com/practice/3350d379a5d44054b219de7af6708894

import java.io.*;
import java.util.*;

public class Main {
    public static void main (String [] args) throws IOException {
        BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));

        String line = null;
        while ((line = f.readLine()) != null)
        {
            int n = Integer.parseInt(line);
            // 这里需要保存名字,因为需要按名字顺序打印
            String[] names = new String[n];
            StringTokenizer st = new StringTokenizer(f.readLine());
            for (int i = 0; i < n; i++)
            {
                names[i] = st.nextToken();
            }
            // n个候选人的名字
            Map<String, Integer> map = new HashMap<>();
            for (String name : names) {
                map.put(name, 0);
            }

            int invalid = 0;
            // m个投票人
            int m = Integer.parseInt(f.readLine());
            st = new StringTokenizer(f.readLine());
            for (int i = 0; i < m; i++) 
            {
                String name = st.nextToken();
                if (map.containsKey(name)) {
                    map.put(name, map.get(name) + 1);
                }
                else {
                    invalid++;
                }
            }
            for (String name : names) {
                out.println(name  + " : " + map.get(name));
            }
            out.println("Invalid : " + invalid);
        }
        out.close();
        f.close();
    }
}
全部评论

相关推荐

评论
1
收藏
分享
牛客网
牛客企业服务