Since it need to record the previous chars, we just have to maintain a queue. Actually, the number of left chars are no larger than 4.
1 // Forward declaration of the read4 API. 2 int read4(char *buf); 3 4 class Solution { 5 private: 6 queue<char> container; 7 public: 8 /** 9 * @param buf Destination buffer 10 * @param n Maximum number of characters to read 11 * @return The number of characters read 12 */ 13 int read(char *buf, int n) { 14 int len = 0, each = INT_MAX; 15 while (!container.empty()) { 16 *buf = container.front(); 17 container.pop(); 18 buf++; 19 len++; 20 } 21 while (len < n && (each = read4(buf))) { 22 len += each; 23 buf += each; 24 } 25 if (len >= n) { 26 for (int i = 0; i < len - n; i++) { 27 container.push(buf[n-len+i]); 28 } 29 buf[n-len] = '\0'; 30 len = n; 31 } 32 return len; 33 } 34 };