leetcode -- Count and Say

来源:互联网 发布:软件 开发 编辑:程序博客网 时间:2024/06/16 10:22

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 = k时的序列,很容易得到n=k+1的序列。递归出口n=1即可。

class Solution {public:    string countAndSay(int n) {    string ret;    if(n == 1){   //递归出口    ret.append(1, '1');    return ret;    }string pre = countAndSay(n - 1);ret = countNext(pre);return ret;    }    string countNext(string s){    int count = 1;    string ret;    for(string::size_type ix = 0; ix < s.size(); ix++){    if(ix + 1 < s.size() && s[ix] == s[ix + 1]){    count++;    continue;    }ret.append(1, '0' + count);ret.append(1, s[ix]);count = 1;}    return ret;    }};


0 0
原创粉丝点击