首页 > 其他 > 详细

[LeetCode]38.Count and Say

时间:2015-01-27 13:24:21      阅读:223      评论:0      收藏:0      [点我收藏+]

【题目】

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.

【分析】

111221 统计相邻重复的字符个数,例如这里111有3个1重复相邻,输出31,22有两个2重复相邻,输出22,1只有一个1,输出11

【代码】

/*********************************
*   日期:2015-01-27
*   作者:SJF0115
*   题目: 38.Count and Say
*   网址:https://oj.leetcode.com/problems/count-and-say/
*   结果:AC
*   来源:LeetCode
*   博客:
**********************************/
#include <iostream>
using namespace std;

class Solution {
public:
    string countAndSay(int n) {
        if(n <= 0){
            return "";
        }//if
        string str("1");
        for(int i = 1;i < n;++i){
            NextCountAndSay(str);
        }//for
        return str;
    }
private:
    void NextCountAndSay(string& str){
        int len = str.length();
        string tmp = "";
        for(int i = 0;i < len;++i){
            int repeatCount = 1;
            // repeat char count
            while((i+1 < len) && (str[i] == str[i+1])){
                ++repeatCount;
                ++i;
            }//
            tmp += to_string(repeatCount);
            tmp += str[i];
        }//for
        str = tmp;
    }
};

int main(){
    Solution solution;
    int n = 5;
    string result = solution.countAndSay(n);
    // 输出
    cout<<result<<endl;
    return 0;
}




[LeetCode]38.Count and Say

原文:http://blog.csdn.net/sunnyyoona/article/details/43192847

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!