BufferedReader比Scanner要快

别人写的博客BufferedReader和Scanner总结点击打开链接

Reader和Scanner比较

BufferedReader是支持同步的,而Scanner不支持。BufferedReader的read函数都加了synchronized关键字
BufferedReader的缓冲区大小为8KB,Scanner的缓冲区大小为1KB

BufferedReader相对于Scanner来说要快一点,因为Scanner对输入数据进行正则解析,而BufferedReader只是简单地读取字符序列。


java解题代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) throws IOException {
        Map<String, String> map = new HashMap<String, String>();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        for (int i = 0; i < n; ++i) {
            String str = br.readLine();
            String[] arr = str.split(" +");
            map.put(arr[1], arr[0] + " " + arr[2]);
        }
        int t = Integer.parseInt(br.readLine());
        String[] sarr = br.readLine().split(" +"); 
        br.close();
        for (int i = 0; i < t; ++i) {
            System.out.println(map.get(sarr[i]));
        }
    }
}

如果用Scanner会超时,Scanner对输入数据进行正则解析,但是BufferedReader只是简单地读取字符序列。所以会过


========================================Talk is cheap, show me the code=======================================

posted @ 2018-03-10 16:51  绿叶萌飞  阅读(222)  评论(0编辑  收藏  举报