python实现leetcode之158. 用 Read4 读取

2021-10-22  本文已影响0人  深圳都这么冷

解题思路

将缓存提到公共区域,其他的如上题

158. 用 Read4 读取 N 个字符 II

代码

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

class Solution:
    def __init__(self):
        self.buf = ['', '', '', '']
        self.finished = False
        self.pool = []

    def read(self, buf: List[str], n: int) -> int:
        nbyte = 0
        while nbyte < n:
            if not self.pool:
                if self.finished:
                    break
                x = read4(self.buf)
                for i in range(x):
                    self.pool.append(self.buf[i])
                if x < 4:
                    self.finished = True
            if self.pool:
                buf[nbyte] = self.pool.pop(0)
                nbyte += 1
        return nbyte
效果图
上一篇下一篇

猜你喜欢

热点阅读