zoukankan      html  css  js  c++  java
  • ✡ leetcode 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.

    和157题一样,区别在于可以对一个文件多次使用read

    那么区别就是在于如果之前调用过一次read,可能由于调用了read4的原因,会出现多读了几个字母(小于4个),那么设定一个变量即可。存储当前多读取的字母长度和字母。

    1、需要注意的点:多次调用的时候,moreChars里的字母可能没有用完。

    /* 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 int len = 0;
        private char[] moreChars = new char[3];
        public int read(char[] buf, int n) {
            if (n < 1){
                return 0;
            }
            int result = 0;
            if (len != 0){
                int count = Math.min(n, len);
                for (int i = 0; i < count; i++){
                    buf[i] = moreChars[i];
                    result++;
                }
                for (int i = 0; i < (len - count); i++){
                    moreChars[i] = moreChars[count + i];
                }
                len -= count;
            }
            char[] chars = new char[4];
            int times = (n - result) / 4;
            for (int i = 0; i < times; i++){
                int count = read4(chars);
                for (int j = 0; j < count; j++){
                    buf[result + j] = chars[j];
                }
                result += count;
                if (count < 4){
                    return result;
                }
            }
            if (n == result){
                return result;
            }
            int count = read4(chars);
            for (int i = 0; i < Math.min(n - result, count); i++){
                buf[result + i] = chars[i];
            }
            if (n - result < count){
                len = count - n + result;
                for (int i = 0; i < len; i++){
                    moreChars[i] = chars[n - result + i];
                }
            }
            result += Math.min(n - result, count);
            return result;
        }
    }
  • 相关阅读:
    css选择器解析规则
    swiper轮播图包含视频或图片
    css实现文字选中变色
    swiper鼠标滚轮事件
    C语言中,关于相除的问题
    输入测试字符型数据的组数,再输入字符型数据,排坑
    C语言中,字符型数字与常数型数字的加减实现
    C语言的指针用法:输入一堆字符,把非字母的删去。
    C语言中倒序输出你输入的数。
    C语言中,嵌套的if语句的一些经验...
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6109605.html
Copyright © 2011-2022 走看看