38. Count and Say

来源:互联网 发布:java 解析swf 编辑:程序博客网 时间:2024/06/15 21:16

The count-and-say sequence is the sequence of integers with the first five terms as following:

1.     12.     113.     214.     12115.     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 term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:

Input: 1Output: "1"

Example 2:

Input: 4Output: "1211"

这道题最简单的思路就是遍历上一个字符串,统计相同字符连续出现的次数,然后输出次数和字符。但是实现的时候很容易出错,需要细心判断在什么情况下才需要输出。

class Solution {public:    string countAndSay(int n) {        if (n == 1) return "1";        //第n-1个字符串        string last = "1";        for (int i = 2; i <= n; i++) {            //第n个字符串            string tmp;            //用来统计c连续出现的次数            int count = 0;            char c = last[0];             for (int j = 0; j < last.size(); j++) {                if (last[j] == c) {                    count++;                }                else {                    tmp += (count + '0');                    tmp += c;                    c = last[j];                    count = 1;                 }                //注意当遍历到最后一个时也要输出                if (j + 1 == last.size()) {                    tmp += (count + '0');                    tmp += c;                }            }            last = tmp;        }        return last;    }};
原创粉丝点击