158. 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 theread4API, implement the functionint read(char *buf, int n)that reads n characters from the file.

Note:
Thereadfunction may be called multiple times.

Example 1:

Given buf = "abc"
read("abc", 1) // returns "a"
read("abc", 2); // returns "bc"
read("abc", 1); // returns ""

Example 2:

Given buf = "abc"
read("abc", 4) // returns "abc"
read("abc", 1); // returns ""

Thoughts:

Having a read4 index to indicate when to read, keep track the index until either the returned value from API is 0 or n is reached

// Forward declaration of the read4 API.
int read4(char *buf);

class Solution {
private:
    char buf4[4];
    int buf4Index = 4;
    int buf4Size = 4;

public:
    /**
     * @param buf Destination buffer
     * @param n   Maximum number of characters to read
     * @return    The number of characters read
     */
    int read(char *buf, int n) {
        int i = 0;
        while(i < n){
            // check calling API condition
            if(buf4Index >= buf4Size){
                buf4Size = read4(buf4);
                if(buf4Size == 0) break;
                buf4Index = 0;
            }
            buf[i] = buf4[buf4Index];
            i++;
            buf4Index++;
        }
        return i;
    }

};

Java

/* 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 int ptr = 0;
    private int count = 0;
    private char[] buff = new char[4];
    public int read(char[] buf, int n) {
        int i = 0;
        while (i < n) {
            if (ptr == 0) {
                count = read4(buff);
            }
            if (count == 0) break;
            while (i < n && ptr < count) {
                buf[i++] = buff[ptr++];
            }
            if (ptr >= count) ptr = 0;
        }
        return i;
    }
}

results matching ""

    No results matching ""