zoukankan      html  css  js  c++  java
  • 158. Read N Characters Given Read4 II

    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.

    Example 1: 

    Given buf = "abc"
    read("abc", 1) // returns "a"
    read("abc", 2); // returns "bc"
    read("abc", 1); // returns ""
    

    Example 2: 

    Given buf = "abc"
    read("abc", 4) // returns "abc"
    read("abc", 1); // returns ""

    reference: 

    https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/discuss/49598/A-simple-Java-code

    https://segmentfault.com/a/1190000003794420

    因为可以调用多次,每一次调用的时候都需要检查上一次是否有未读完的字符串,从上一次未读完的接着读。

    e.g.
    Given buf = "abc" tmp = {0,0,0,0}, count = 0, ptr = 0
    read("abc", 1); // returns "a"
    -> index = 0, n = 1, count = read4(tmp) = 4, buf[0]=tmp[0] -> index = 1, ptr = 1, return index = 1
    read("abc", 2); // returns "bc"
    -> index = 0, n = 2, count = read4(tmp) = 4, buf[0]=tmp[1],buf[1]=tmp[2] -> index = 2, ptr = 3, return index = 2
    read("abc", 1); // returns ""
    -> index = 0, n = 1, count = read4(tmp) = 4, buf[0]=tmp[3] -> index = 1, ptr = 4 -> ptr = 0, return index = 1

    time: O(N), space: O(1)

    /* The read4 API is defined in the parent class Reader4.
          int read4(char[] buf); */
    
    public class Solution extends Reader4 {
        /**
         * @param buf Destination buffer
         * @param n   Maximum number of characters to read
         * @return    The number of characters read
         */
        private char[] tmp = new char[4];
        private int count = 0;
        private int ptr = 0;
        
        public int read(char[] buf, int n) {
            int index = 0;
            while(index < n) {
                if(ptr == 0) {
                    count = read4(tmp);
                }
                if(count == 0) break;
                while(index < n && ptr < count) {
                    buf[index++] = tmp[ptr++];
                }
                if(ptr == count) ptr = 0;
            }
            return index;
        }
    }
  • 相关阅读:
    卡尔曼滤波公式
    在博客园主页添加github链接
    博客园插入latex公式
    Leetcode刷题(2020/03/20)
    git设置http代理
    ubuntu下解压.zip文件乱码
    Linux系统中的变量PATH
    【windows】在控制面板卸载软件的时候,出现2502,2503的问题
    替换openjdk的版本时遇到报错Transaction check error
    安装Python3.6.4后,在使用numpy时报错RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10141096.html
Copyright © 2011-2022 走看看