Java, more general solution. easy.


  • 0
    Z
    /* 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
         */
         
        char[] buff = new char[4];
        int size = 0;
        int used = 0;
        
        public int read(char[] b, int n) {
            int ret = 0;
            
            while(ret < n){
                // reload cache
                if(used == size){
                    size = read4(buff);
                    used = 0;
                    
                    if(size == 0)
                        break;
                        
                }
                while(used < size && ret < n)
                    b[ret++] = buff[used++];
            }
            
            return ret;
        }
    }

Log in to reply
 

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