5/01/2021

[LeetCode] 158. Read N Characters Given Read4 II - Call multiple times

 Problem : https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/

The difference to problem 157 is the read() can be called multiple times. So we need to remember the reading position since last time the API be called.

Use queue as intermediate buffer to simplify the reading logic.


# The read4 API is already defined for you.
# def read4(buf4: List[str]) -> int:

class Solution:
    def __init__(self):
        self.queue = deque()
        
    def read(self, buf: List[str], n: int) -> int:
        copied = 0
        buf4 = [''] * 4
        
        while copied < n:
            while self.queue:
                buf[copied] = self.queue.popleft()
                copied += 1
                
                if copied == n:
                    return copied
            
            read = read4(buf4)
            if read == 0:
                return copied
            
            for i in range(read):
                self.queue.append(buf4[i])
        
        return copied

No comments:

Post a Comment