Count and Say

標簽: C++ 算法 LeetCode 字符串 遞歸

每日算法——leetcode系列


問題 Count and Say

Difficulty: Easy

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" or21.
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 countAndSay(int n) {
        
    }
};

翻譯

數(shù)數(shù)并報數(shù)

難度系數(shù):容易

數(shù)數(shù)并報數(shù)順序按如下規(guī)律開始遞增:
1,11,21,1211,111221,……

1 讀作“1個1”11
11 讀作“2個1”21
21 讀作“1個21個1”得1211

給定一個整數(shù)n,生成第n個序列。

注意:數(shù)字序列應(yīng)該用字符串表示。

思路

此題我覺得英文的表面意思跟實際要的不一樣。
題意:數(shù)上次字符串中的連續(xù)出現(xiàn)數(shù)值的個數(shù), 將這些字符串拼接起來

  • n=1時,輸出字符串1;
  • n=2時,因為上次字符串1,1連續(xù)出現(xiàn)1次,就是1個1,所以輸出11;
  • n=3時,由于上次字符串11,其中1連續(xù)出現(xiàn)兩次,就是2個1,所以輸出21;
  • n=4時,由于上次字符串是21,其中2出現(xiàn)1次,1出現(xiàn)1次,所以輸出1211;
  • n=5時,由于上次字符串1211,第個1連續(xù)出現(xiàn)1次為11,第二個2連續(xù)出現(xiàn)1次為12,第三個1跟第四個1連續(xù)出現(xiàn)了2次,為21,所以輸出111221

代碼

#include <iostream>
#include <sstream>
using namespace std;

class Solution {

public:
     string countAndSay(int n) {
        if(n == 1){
            return "1";
        }
        //遞歸調(diào)用
         string str = countAndSay(n-1);
        int len = static_cast<int>(str.length());
        int count = 1;
        stringstream s;
        for(int i = 0; i < len; ++i){
            if(str[i] == str[i+1]){
                count++;
            } else {
                s << count << str[i];

                count = 1;
            }
        }
        return s.str();
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容