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

[LeetCode]38.Count and Say

时间:2015-01-27 13:25:04      阅读:167      评论:0      收藏:0      [点我收藏+]

标签: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.

【分析】

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

标签:leetcode

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

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