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;
    }
};
原文地址:https://www.cnblogs.com/tonix/p/4754347.html