leetcode count and say

問題描述:

https://oj.leetcode.com/problems/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.

問題分析:

通過最當前數字序列cur數數, 產生下一個序列next;

1(1個1) --> 11(2個1)--> 21-->  1211

對於輸入n, 需要迭代 n - 1 次得到所需要的序列,序列產生的方法

如上邊所示。重點在於統計字符s[i]出現的次數,重新拼接成新的字符串。

示例代碼:

string countAndSay(int n) 
    {
        string cur = "1";
        for (int i = 1; i < n; i++)
        {   
            int m = cur.length();
            int num = 1;
            char ch = cur[0];
            stringstream next; /* 採用字符串流進行輔助字符串拼組 */
            for (int j = 1; j < m; j++)
            {
                if (cur[j] == ch)
                {   num++;  } /* 統計計數 */
                else
                {
                    next << num << ch; /* 遇到新字符,舊字符統計完成,開始拼接 */
                    ch = cur[j]; num = 1;
                }
            }
            next << num << ch;
            cur = next.str();
        }
        return cur;
    }


發佈了149 篇原創文章 · 獲贊 8 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章