Count and Say

来源:互联网 发布:linux命令行测试网速 编辑:程序博客网 时间:2024/06/05 20:49

一、问题描述

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.

二、思路

利用辅助函数通过递推关系求出下一个countAndSay.

三、代码

class Solution {public:    string convertTocountAndSay(string s){        int p = 0;        string res = "";        while(p < s.length()){            int count = 0;            char cur_num = s[p];            while(p < s.length() && s[p] == cur_num) {count++;p++;}            res += count + '0';            res += cur_num;        }        return res;    }    string countAndSay(int n) {        string res = "1";        int count = 1;        while(count < n){            res = convertTocountAndSay(res);            ++count;        }        return res;    }};


0 0