码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Count and Say

时间:2015-05-03 22:10:38      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   

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=1,那么为s[n]="1"

若n>0,那么逐个读取s[n-1]中相同的字符,然后说k个这个字符,直到s[n-1]读玩为止。比如111221可以这么读,3个1,2个2,1个1,于是下一个字串为312211。

显然用递归最合适。

class Solution {
public:
    string countAndSay(int n) {
        if(n==1){
            return "1";
        }
        string s=countAndSay(n-1);
        int len=s.length();
        string result="";
        char lastChar=s[0];
        int count=1;
        char charNum;
        for(int i=1; i<len; i++){
            if(s[i]==lastChar){
                count++;
                continue;
            }
            charNum = count + '0';
            result = result + charNum + lastChar;
            lastChar=s[i];
            count=1;
        }
        charNum = count + '0';
        result = result + charNum + lastChar; //注意这里有个陷阱,在循环外需要这么加
        return result;
    }
};


[LeetCode] Count and Say

标签:c++   leetcode   

原文地址:http://blog.csdn.net/kangrydotnet/article/details/45461567

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!