157_Read N Characters Given Read4

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 will only be called once for each test case.

Solution

用一个临时数组buf4,存放每次read4读到字符,再用一个指针标记buf数组目前存储到的位置,然后将这个临时数组的内容存到buf相应的位置就行了。这里需要注意两个corner case:

  1. 如果本次读到多个字符,但是我们只需要其中一部分就能完成读取任务时,我们要拷贝的长度是本次读到的个数和剩余所需个数中较小的curr = min(read4(buf4),n-idx)

  2. 如果read4没有读满4个,说明数据已经读完,这时候对于读到的数据长度,因为也可能存在我们只需要其中一部分的情况,所以要返回总所需长度和目前已经读到的长度的较小的return idx

class Solution(object):
    def read(self, buf, n):
        """
        :type buf: Destination buffer (List[str])
        :type n: Maximum number of characters to read (int)
        :rtype: The number of characters read (int)
        """
        idx = 0
        while True:
            buf4 = [""]*4
            curr = min(read4(buf4),n-idx)  # curr is the number of chars that reads
            for i in xrange(curr):
                buf[idx] = buf4[i]
                idx += 1
            if curr!=4 or idx==n:  # return if it reaches the end of file or reaches n
                return idx

Last updated