Friday, July 15, 2016

158. Read N Characters Given Read4 II - Call multiple times

I was thinking every time you call read, it will read the file from beginning, but it seems not. The following solution fails case ["ab", read(1), read(2)], output should be ["a", "b"]. From the output, I realized that when calling read(), it should maintain the file offset.

1:  class Solution {  
2:  public:  
3:    /**  
4:     * @param buf Destination buffer  
5:     * @param n  Maximum number of characters to read  
6:     * @return  The number of characters read  
7:     */  
8:    int read(char *buf, int n) {  
9:      int i = 0;  
10:      int m = 0;  
11:      int rc = 0;  
12:      while (i < n && (m = read4(buf)) > 0) {  
13:        buf += m;  
14:        i += m;  
15:      }  
16:      return i >= n ? n : i;  
17:    }  
18:  };  

So we need to have a 4 bytes buffer and its pointer as the file offset.

1:  // Forward declaration of the read4 API.  
2:  int read4(char *buf);  
3:  class Solution {  
4:  private:  
5:    char buffer[4];  
6:    int ib = 0;  
7:    int nb = 0;  
8:  public:  
9:    /**  
10:     * @param buf Destination buffer  
11:     * @param n  Maximum number of characters to read  
12:     * @return  The number of characters read  
13:     */  
14:    int read(char *buf, int n) {  
15:      int i = 0;  
16:      while ((i < n) && (ib < nb || (ib = 0) < (nb = read4(buffer)))) {  
17:        buf[i++] = buffer[ib++];  
18:      }  
19:      return i;  
20:    }  
21:  };  

No comments:

Post a Comment