Read N Characters Given Read4 II - Call multiple times

Problem: Read N Characters Given Read4 II - Call multiple times

The basic idea of the solution is read 4 characters if necessary and read less than 4 characters if no need for 4 letters. We use a universal queue to manage this so that the function can be called several times. Note that the argument "buf" in this function or the "buf4" passed into read4 are used to store the read-out result not the to-read string.

Code in Python:

class Solution(object):
    def __init__(self):
        self.queue = []

    def read(self, buf, n):
        idx = 0
        while True:
            buf4 = [""] * 4
            l = read4(buf4)
            self.queue.extend(buf4)
            curr = min(len(self.queue), n-idx)
            for i in xrange(curr):
                buf[idx] = self.queue.pop(0)
                idx+=1
            if curr == 0:
                break 
        return idx

results matching ""

    No results matching ""