2015年9月10日星期四

Read N Characters Given Read4 II - Call multiple times

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 may be called multiple times.

/* The read4 API is defined in the parent class Reader4.
      int read4(char[] buf); */

public class Solution extends Reader4 {
    /**
     * @param buf Destination buffer
     * @param n   Maximum number of characters to read
     * @return    The number of characters read
     */
 
    private char[] buf4 = new char[4];
 
    private int start = 0;
    private int end = 0;
 
    public int read(char[] buf, int n) {
        int cur = 0;
        while (start < end && cur < n) {
            buf[cur++] = buf4[start++];
        }
        while (cur < n) {
            int len = read4(buf4);
            start = 0;
            end = len;
            while (start < end && cur < n) {
                buf[cur++] = buf4[start++];
            }
            if (len < 4 || cur == n) {
                break;
            }
        }
        return cur;
    }
}

===========

/* The read4 API is defined in the parent class Reader4.
      int read4(char[] buf); */

public class Solution extends Reader4 {
    /**
     * @param buf Destination buffer
     * @param n   Maximum number of characters to read
     * @return    The number of characters read
     */
    char[] buf4 = new char[4];
    int from = 4;
    int cap = 0;
 
    public int read(char[] buf, int n) {
        int idx = 0;
        boolean stop = false;
        while (true) {
            while (from < cap) {
                if (idx == n) {
                    stop = true;
                    break;
                }
                buf[idx++] = buf4[from++];
            }
            if (stop) {
                break;
            }
            from = 0;
            cap = read4(buf4);
            if (cap < 4) {
                stop = true;
            }
        }
        return idx;
    }
}

=================

/* The read4 API is defined in the parent class Reader4.
      int read4(char[] buf); */

public class Solution extends Reader4 {
    /**
     * @param buf Destination buffer
     * @param n   Maximum number of characters to read
     * @return    The number of characters read
     */
   
    private char[] buf4 = new char[4];
    private int start = 4;
    private int cap = 4;
   
    public int read(char[] buf, int n) {
        int idx = 0;
        while (true) {
            while (start < cap && idx < n) {
                buf[idx++] = buf4[start++];
            }
            if (cap != 4 || n == idx) break;
            cap = read4(buf4);
            start = 0;
        }
        return idx;
    }
}

没有评论:

发表评论