Leetcode 158 Read N Characters Given Read4 II

来源:互联网 发布:梵高色盲知乎 编辑:程序博客网 时间:2024/05/22 05:31

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.

和157不同的地方在于,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[] buffer = new char[4];     private int pointer = 0;//buffer的pointer    private int counter = 0;//buffer的counter    public int read(char[] buf, int n) {          int ptr = 0;//buf        while(ptr < n){            if(pointer == 0){                counter = read4(buffer);            }                                    while(ptr < n && pointer < counter){                buf[ptr++] = buffer[pointer++];            }                                    if(pointer == counter){                pointer = 0;            }            //end of file            if(counter < 4){                  break;            }                    }        return ptr;      }  }