@@ -0,0 +1,1968 @@
+package data_structure.stream;%0A%0Apublic class ReadNCharactersGivenRead4 %7B%0A%0A    //TAG: Facebook%0A    //TAG: stream%0A    //Difficulty: Easy%0A%0A    /**%0A     * 157. Read N Characters Given Read4%0A     * The API: int read4(char *buf) reads 4 characters at a time from a file.%0A     *%0A     * 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.%0A     *%0A     * By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.%0A     *%0A     * Example 1:%0A     *%0A     * Input: buf = %22abc%22, n = 4%0A     * Output: %22abc%22%0A     * Explanation: The actual number of characters read is 3, which is %22abc%22.%0A     * Example 2:%0A     *%0A     * Input: buf = %22abcde%22, n = 5%0A     * Output: %22abcde%22%0A     * Note:%0A     * The read function will only be called once for each test case.%0A     */%0A%0A    /*%0A     * Solution:%0A     * Key point here is:%0A     *  1. when n %3E 4, need continue read4 and fill buff and until n chars filled%0A     *  2. when e.g. 3 chars left need to fill, cannot fill all 4 chars from new read4, but first 3 chars from new read4%0A     *%0A     *  so keep read4 and fill to buf until read4 n chars filled or read4 not enough 4 chars and all filled%0A     *%0A     *  Time: O(min(sizeOf(file), n))%0A     *  Space: O(1)%0A     */%0A%0A    public int read(char%5B%5D buf, int n) %7B%0A        char%5B%5D temp = new char%5B4%5D;%0A        //Index represent current index of buf and final length filled%0A        int index = 0;%0A        while (index %3C n) %7B%0A            int count = read4(temp);%0A            //count is the correct length but not 4, due to read4 may not have enough 4 chars%0A            for (int i = 0; i %3C count && index %3C n; i++)%0A                buf%5Bindex++%5D = temp%5Bi%5D;%0A            //if read4 has not enough 4 chars, need to break the loop, will has no more chars%0A            if (count %3C 4) break;%0A        %7D%0A        return index;%0A    %7D%0A%0A    int read4(char%5B%5D buf) %7B%0A        return 0;%0A    %7D%0A%0A%7D%0A

157. Read N Characters Given Read4