zoukankan      html  css  js  c++  java
  • LeetCode "Read N Characters Given Read4 II

    I learnt a clean idea: all read is from the 4-char buffer.

    int read4(char *buf);
    class Solution {
        int offset;
        int validLen;
        char _buf[4];
        
        void _readBuffer(char *&buf, int &len, int n)
        {
            for (; offset < validLen && len < n; offset++)
            {
                *(buf++) = _buf[offset];
                len++;
            }
        }
    public:
        Solution() : offset(0), validLen(0){}
        
        //    Point: all through _buf, as a buffercache
        int read(char *buf, int n) {
            int len = 0;
            // read carry over bytes first, if any
            _readBuffer(buf, len, n);
            
            //    main
            while (len < n)
            {
                //  reload cache
                validLen = read4(_buf);    offset = 0;
                
                _readBuffer(buf, len, n);
                
                if (validLen < 4) break;
            }
            return len;
        }
    };
  • 相关阅读:
    Kattis
    Kattis
    Kattis
    Kattis -Backspace
    Kattis
    Kattis
    Kattis
    Hihocoder1061-Beautiful String
    Hihocoder1350-Binary Watch
    Hihocoder1458-Parentheses Matching(stack,vector)
  • 原文地址:https://www.cnblogs.com/tonix/p/4754347.html
Copyright © 2011-2022 走看看