推荐解法:
设置成员变量offset,长度为4的列表buffer,buffer中的字符串长度bufsize。在调用read时,先利用bufsize和offset判断buffer中是否存在尚未被输出的字符。如果存入buf中,判断buf中存储的字符串长度还未到达n或read4的指针还未来到终点,则循环调用read4将所需长度的字符串加入buf并重复上一个判断,直到条件不满足。
Python源码,来自ycsung:
该方法采用queue数据结构,简洁优雅地实现了read方法。赞。
class Solution(object):
def __init__(self):
self.queue = []
def read(self, buf, n):
"""
:type buf: Destination buffer (List[str])
:type n: Number of characters to read (int)
:rtype: The number of actual characters read (int)
"""
idx = 0
while True:
buf4 = ['']*4
l = read4(buf4)
self.queue.extend(buf4)
curr = min(len(self.queue), n-idx)
for i in range(curr):
buf[idx] = self.queue.pop(0)
idx += 1
if curr == 0:
break
return idx
我的心路:
思路和推荐解法类似,但1个半小时也没能实现出来。(┬_┬)
默写了一下上面的方法。
Runtime: 20 ms, faster than 58.10% of Python online submissions for Read N Characters Given Read4 II - Call multiple times.
Memory Usage: 11.9 MB, less than 100.00% of Python online submissions for Read N Characters Given Read4 II - Call multiple times.
class Solution(object):
def __init__(self):
self.queue = []
def read(self, buf, n):
"""
:type buf: Destination buffer (List[str])
:type n: Number of characters to read (int)
:rtype: The number of actual characters read (int)
"""
idx = 0
while True:
buf4 = ['']*4
l = read4(buf4)
self.queue.extend(buf4[:l])
curr = min(len(self.queue), n - idx)
for i in range(curr):
buf[idx] = self.queue.pop(0)
idx += 1
if curr == 0:
return idx