Count and Say,countandsay

來源:互聯網
上載者:User

Count and Say,countandsay

一、 題目

題目說,如下的字串:

1, 11, 21, 1211, 111221, ...

1讀成11(一個1)

11讀成21(兩個1)

21讀成(一個2一個1)

......

給一個整數,返回對應得語句。返回語句為一個字串

二、 分析

題目的意思不是很明白,其實就是說第i+1個字串是第i個字串的讀法,第一字串為 “1”

比如第四個字串是1211,它的讀法是 1個1、1個2,2個1,因此第五個字串是111221。第五個字串的讀法是:3個1、2個2、1個1,因此第六個字串是312211。

明白了題意,我們不難想到思路:

1、初始字串為”1”,字元ch為 str[0],中間字串為str2;

2、從1開始迴圈產生字串直到n;

3、遍曆字串,計數相連的相同字元,併產生新的字串; 

 

class Solution {public:    string countAndSay(int n) {        if(n == 0)        return "";        string str = "1";        for(int i = 1; i < n; i++){        char ch = str[0];        string str2 = "";        int count = 1;        for(int j=1;j<str.size();j++){        if (str[j] == ch)        count ++;        else if(count > 0){        str2 = str2 + char(count + '0') + ch;        count = 1;        ch = str[j];}}        str2 = str2 + char(count + '0') + ch;        str = str2;        }        return str;    }};

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.