码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]Read N Characters Given Read4

时间:2020-02-07 16:35:00      阅读:78      评论:0      收藏:0      [点我收藏+]

标签:amp   with   def   elf   bre   拷贝   etc   self   ready   

先用read4拷贝到buf4,然后从buf4里读:

"""
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 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)
        """
        
        buf4 = [‘ ‘] * 4
        buf4Start = 0
        buf4End = 0
        isEof = False
        
        cnt = 0
        while cnt < n:
            if isEof and buf4Start >= buf4End: # nothing to read
                break
            elif buf4Start < buf4End: # copy from buf4
                buf[cnt] = buf4[buf4Start]
                cnt += 1
                buf4Start += 1
            else: # no more in buf4, read4
                buf4End = read4(buf4)
                buf4Start = 0
                if buf4End == 0:
                    isEof = True
                
        return cnt

  

[leetcode]Read N Characters Given Read4

标签:amp   with   def   elf   bre   拷贝   etc   self   ready   

原文地址:https://www.cnblogs.com/lautsie/p/12273183.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!