This problem is tagged Hard, and for me the main hard part is how to understand the question:
- will read4(ary) totally overwrite ary or only cover the front part? (overwrite)
- do I need to return the read result so far or only this time result?(only this time)
- what does "The read function may be called multiple times." exactly mean?(a fixed file could be called multiple times read())
Firstly it's crucial to know what the problem is about. I would like to refer @laonawuli explanation here:
Think that you have 4 chars "a, b, c, d" in the file, and you want to call your function twice like this:
read(buf, 1); // should return 'a'
read(buf, 3); // should return 'b, c, d'
All the 4 chars will be consumed in the first call. So the tricky part of this question is how can you preserve the remaining 'b, c, d' to the second call.
Then is doing read(): digest all the existing cached elements before do exactly the same as this one
from collections import deque class Solution(object): def __init__(self): self.q = collections.deque() def read(self, buf, n): idx, buffer = 0, [''] * 4 while idx < n and self.q: buf[idx], idx = self.q.popleft(), idx + 1 while idx < n: rcnt = read4(buffer) if not rcnt: return idx buf[idx: idx + rcnt], idx = buffer[:rcnt], idx + rcnt if idx > n: for i in xrange(n, idx): self.q.append(buf[i]) buf = buf[:n] return n