首页>itarticle>158. read n characters given read4 ii
158. read n characters given read4 ii
admin11月 12, 20200
# The API: int read4(char *buf) reads 4 characters at a time from a file.## The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.## By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.## Note:# The read function may be called multiple times.## The read4 API is already defined for you.# @param buf, a list of characters# @return an integerdefread4(buf):globalfile_contenti=0whilei<len(file_content)andi<4:buf[i]=file_content[i]i+=1iflen(file_content)>4:file_content=file_content[4:]else:file_content=""returniclassSolution(object):def__init__(self):self.remain=''defread(self,buf,n):""" :type buf: Destination buffer (List[str]) :type n: Maximum number of characters to read (int) :rtype: The number of characters read (int) """start=0buffer=['']*4copyn=nifself.remain:# read remain part from the last calllength=len(self.remain)ifcopyn>length:# append remain firstlybuf[start:start+length]=self.remainstart+=lengthcopyn-=lengthelse:buf[start:start+length]=self.remain# append add remain, no file leftstart+=lengthreturnmin(start,n)whilecopyn>0:# if any group leftsize=read4(buffer)ifcopyn>=4:buf[start:start+size]=bufferstart+=4copyn-=4else:# if remain group length is 1-3buffer=buffer[:size]# only slice with size length from 4gap=min(copyn,size)# get the minimum of copyn and sizebuf[start:start+gap]=buffer[:gap]self.remain=buffer[gap:]# remain partstart+=gapbreakreturnmin(start,n)if__name__=="__main__":globalfile_contentanswer=Solution()buf=[''foriinrange(100)]file_content="abcdefg"printbuf[:answer.read(buf,5)]printbuf[:answer.read(buf,3)]
近期评论