1. 程式人生 > >[LeetCode] Read N Characters Given Read4 用Read4來讀取N個字元

[LeetCode] Read N Characters Given Read4 用Read4來讀取N個字元

The API: int read4(char *buf) reads 4 characters at a time from a file.
The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.
By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.
Note:
The read function will only be called once for each test case.

這道題給了我們一個Read4函式,每次可以從一個檔案中最多讀出4個字元,如果檔案中的字元不足4個字元時,返回準確的當前剩餘的字元數。現在讓我們實現一個最多能讀取n個字元的函式。這題有迭代和遞迴的兩種解法,我們先來看迭代的方法,思路是我們每4個讀一次,然後把讀出的結果判斷一下,如果為0的話,說明此時的buf已經被讀完,跳出迴圈,直接返回res和n之中的較小值。否則一直讀入,直到讀完n個字元,迴圈結束,最後再返回res和n之中的較小值,參見程式碼如下:

解法一:

// Forward declaration of the read4 API.
int read4(char *buf);

class Solution { public: int read(char *buf, int n) { int res = 0; for (int i = 0; i <= n / 4; ++i) { int cur = read4(buf + res); if (cur == 0) break; res += cur; } return min(res, n); } };

下面來看遞迴的解法,這個也不難,我們對buf呼叫read4函式,然後判斷返回值t,如果返回值t大於等於n,說明此時n不大於4,直接返回n即可,如果此返回值t小於4,直接返回t即可,如果都不是,則直接返回呼叫遞迴函式加上4,其中遞迴函式的buf應往後推4個字元,此時n變成n-4即可,參見程式碼如下:

解法二:

// Forward declaration of the read4 API.
int read4(char *buf);

class Solution {
public:
    int read(char *buf, int n) {
        int t = read4(buf);
        if (t >= n) return n;
        if (t < 4) return t;
        return 4 + read(&buf[4], n - 4);
    }
};

類似題目:

參考資料: