zoukankan      html  css  js  c++  java
  • [leetcode]Read N Characters Given Read4 II

    调用多次readN,所以要重复使用internal buffer

    """
    The read4 API is already defined for you.
    
        @param buf, a list of characters
        @return an integer
        def read4(buf):
    
    # Below is an example of how the read4 API can be called.
    file = File("abcdefghijk") # File is "abcdefghijk", initially file pointer (fp) points to 'a'
    buf = [' '] * 4 # Create buffer with enough space to store characters
    read4(buf) # read4 returns 4. Now buf = ['a','b','c','d'], fp points to 'e'
    read4(buf) # read4 returns 4. Now buf = ['e','f','g','h'], fp points to 'i'
    read4(buf) # read4 returns 3. Now buf = ['i','j','k',...], fp points to end of file
    """
    class Solution:
        def __init__(self):
            self.buf4 = [' '] * 4
            self.buf4Start = 0
            self.buf4End = 0
            self.isEof = False
            
            
        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)
            """
            
            cnt = 0
            while cnt < n:
                if self.isEof and self.buf4Start >= self.buf4End: # nothing to read
                    break
                elif self.buf4Start < self.buf4End: # copy from buf4
                    buf[cnt] = self.buf4[self.buf4Start]
                    cnt += 1
                    self.buf4Start += 1
                else: # no more in buf4, read4
                    self.buf4End = read4(self.buf4)
                    self.buf4Start = 0
                    if self.buf4End == 0:
                        self.isEof = True
                    
            return cnt
    

      

  • 相关阅读:
    舌尖上的中关村
    解决winform窗体闪烁问题
    24段魔尺,可以折出哪些精美图案(续)
    24段魔尺,可以折出哪些精美图案
    关于Python编程的一些问答
    BZOJ 1025: [SCOI2009]游戏
    BZOJ 1025: [SCOI2009]游戏
    BZOJ 1207: [HNOI2004]打鼹鼠
    BZOJ 1207: [HNOI2004]打鼹鼠
    BZOJ 1046: [HAOI2007]上升序列
  • 原文地址:https://www.cnblogs.com/lautsie/p/12273889.html
Copyright © 2011-2022 走看看