File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11// https://oj.leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times/
22
3- // Forward declaration of the read4 API.
43int read4 (char *buf);
54
65class Solution {
76public:
8- char tmpBuf[4 ];
9- int tmpStart = 0 ;
10- int tmpEnd = 0 ;
11- bool eof = false ;
7+
8+ char myBuf[4 ];
9+ int myBufStart = 0 ;
10+ int myBufLen = 0 ;
11+
1212 /* *
1313 * @param buf Destination buffer
1414 * @param n Maximum number of characters to read
1515 * @return The number of characters read
1616 */
1717 int read (char *buf, int n) {
18- if (n == 0 ) return 0 ;
19-
20- int count = 0 ;
18+ int readBytes = 0 ;
19+ int bufStart = 0 ;
2120 bool eof = false ;
22- do {
23- int tmpLen = tmpEnd - tmpStart;
24- int copyCount = min (tmpLen, n - count);
25- if (copyCount > 0 ) {
26- memcpy (buf + count, tmpBuf + tmpStart, copyCount);
27- count += copyCount;
28- tmpStart += copyCount;
21+ while (!eof && readBytes < n) {
22+ if (myBufLen == 0 ) {
23+ myBufLen = read4 (myBuf);
24+ myBufStart = 0 ;
25+ if (myBufLen < 4 ) eof = true ;
2926 }
30- if (eof || n == count) {
31- break ;
32- } else {
33- int readCount = read4 (tmpBuf);
34- tmpStart = 0 ;
35- tmpEnd = readCount;
36- if (readCount < 4 ) {
37- eof = true ;
38- }
39- }
40- } while (true );
41-
42- return count;
27+ int copiedBytes = min (myBufLen, n - readBytes);
28+ memcpy (buf + bufStart, myBuf + myBufStart, copiedBytes);
29+ myBufStart += copiedBytes;
30+ myBufLen -= copiedBytes;
31+ bufStart += copiedBytes;
32+ readBytes += copiedBytes;
33+ }
34+ return readBytes;
4335 }
4436};
You can’t perform that action at this time.
0 commit comments