Read N Characters Given Read4

题目地址:
https://leetcode.com/problems/read-n-characters-given-read4/#/description

题目:
The API: int read4(char *buf) reads 4 characters at a time from a file.
The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.
By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.
Note:
The read function will only be called once for each test case.

解题思路:
这道题主要是要理解read4这个api的用法。它是将file里面的4个char读出来存到buf里面并且返回读到的char的个数。这里有一个follow up,就是如果有多次调用read function,那么就需要保存之前consumed的char。Think that you have 4 chars "a, b, c, d" in the file, and you want to call your function twice like this:
  1. read(buf, 1); // should return 'a'
  2. read(buf, 3); // should return 'b, c, d'
All the 4 chars will be consumed in the first call. So the tricky part of this question is how can you preserve the remaining 'b, c, d' to the second call.

代码:

public int read(char[] buf, int n) {
    int p = 0;
    while(p < n){
        char[] temp = new  char[4];
        int k = read4(temp);
        for(int i = 0; i < k && p < n; i++){
            buf[p++] = temp[i];
        }
        if(k < 4){
            return p;
        }
    }
    return p;
}

follow up:

    private int buffPtr = 0;
    private int k = 0;
    char[] temp = new char[4];
    public int read(char[] buf, int n) {
        int p = 0;
        while(p < n){
            if(buffPtr == 0){
                k = read4(temp);
            }
            if(k == 0){
               break;
            }
            while(p < n && buffPtr < k){
               buf[p++] = temp[buffPtr++];
            }
            if(buffPtr >= k){
               buffPtr = 0;
            }
        }
        return p;
    }


Comments

Popular Posts