Damn simple java


  • 0
    Z
    /* The read4 API is defined in the parent class Reader4.
          int read4(char[] buf); */
    
    public class Solution extends Reader4 {
        char[] cache = new char[4] ;
        /*chache pointers*/
        int start =0;
        int end =0; // exclusive
            
        /**
         * @param buf Destination buffer
         * @param n   Maximum number of characters to read
         * @return    The number of characters read
         */
        public int read(char[] buf, int n) {
            int idx =0;
            int remain = n;
            
            /*fill chars one by one*/
            while(remain > 0){
                if(start != end){ // cache has contents, copy one char
                    buf[idx++] = cache[start++];
                    remain --;
                }
                else{
                    // cache is empty, reload.
                    start = end =0;
                    end  = read4(cache);
                    
                    if(end == 0) // nothing to read.
                        break;
                }
            }
            
            return idx;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.