LeetCode演算法題之Count and Say__演算法

來源:互聯網
上載者:User
//問題描述
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.


//.................................................................//

//理解錯了題意,這寫的是輸入一個正整數N,則輸出他的第N個變形,其實這更具靈活性

class Solution{public:    string countAndSay(int n)    {        if(n<=0)            return "";        if(n == 1)            return "1";        int sequenceLength = n-2;//此處很詭異啊,要是不減去2,下面的while迴圈會多迴圈2次,實際上很好理解,sequence是輾轉調用的        stringstream itos;        itos<<n;        string sequence = "1" + itos.str(); //將數字轉為字串        while(sequenceLength >0)        {   //反覆調用            sequence = printSequence(sequence);            sequenceLength--;        }        return sequence;    }    string printSequence(string str)    {        string tempString;        unsigned int i=0;        int index=0;        unsigned int j=0;        while(j<str.length())        {            if(str[i] == str[j])            {                index++;                if(j+1 == str.length())                {  //最後一個數位比較,下面的else語句將不再執行,只能在此處執行,否則將會把它漏掉                    tempString = tempString + (char)(index+'0') +(char)str[i];                    break;                }            }            else            {                tempString = tempString + (char)(index+'0') +(char)str[i];                i = j;//從下一個不同處開始計算某個數的連續存在次數,比如112211,數字1連續存在兩次後,      //變成2,此處的str[i]將變成2開始往下統計2的連續存在次數                j--;  //j一定要退回一格,保持str[i]將變成2的同時str[j]還是2                index = 0;            }            j++;        }        return tempString;    }};
//只是對1這個數而言,輸入一個整數n,輸出1的第n次變形,不過沒關係,用下面的
//代碼將上面理解錯誤的代碼中第一個while迴圈前的代碼替換掉即可AC

if(n<0)    return "";if(n == 1)    return "1";int sequenceLength = n-2;string sequence = "11" ;

網上其他大神寫的比我的簡潔的多,沒辦法,笨啊。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.