[Leetcode] 118. Count and Say

題目

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...

1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.

Given an integer n, generate the nth sequence.

Note: The sequence of integers will be represented as a string.

解題之法

class Solution {
public:
    string getNext(string s)
    {
        if (s == "") return "1";
        string ans = "";
        int len = s.size(), cnt = 1; // 計數cnt初始為1,因為一旦出現一個數那至少是一次
        for (int i = 0; i < len; i++)
        {
            if (i+1 < len && s[i+1] == s[i])
            {
                cnt++;continue;
            }
            ans += cnt + '0'; // 和下面的s[i]要分開來加,否則會先進行字符串相加再到ans中
            ans += s[i];
            cnt = 1; //記錄后記得將cnt恢復為1
        }
        return ans;
    }
    string countAndSay(int n) 
    {
        if (n == 0)
            return "";
        string ans = "";
        for (int i = 0; i < n; ++i) // 重復找n次next的就可以了
            ans = getNext(ans);
        return ans;
    }
};

分析

題目的意思是按照一定的規則出現數字,以字符串的形式。規定第一個是1,接下去就是按照前一個數的讀法記錄,所以第二個就是1個1,記錄為11,那第三個就是對11的讀法就是2個1,記錄為21,第四個就是對21的讀法,一個2一個1,記錄為1211,以此類推。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容