leetcode No38. Count and Say

来源:互联网 发布:军团要塞2 知乎 编辑:程序博客网 时间:2024/06/06 07:07

Question:

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.

给数字编码,1代表1,2代表11,3代表21,4代表1211
即n对应的字符串是n-1对应的字符串编码

Algorithm:

迭代即可

Accepted Code:

class Solution {public:    string work(string s)    {        int k=0;        string t;        while(k<s.size())        {            int tmp=s[k];            int count=0;            while(s[k]==tmp)            {                k++;                count++;            }            t.push_back(count+'0');            t.push_back(tmp);        }        return t;    }    string countAndSay(int n) {        if(n==1)return "1";        string tmp="1";        while(--n)        {            tmp=work(tmp);    //迭代                            }        return tmp;    }};


0 0
原创粉丝点击