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

LeetCode Count and Say

时间:2014-07-16 17:02:13      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   for   io   div   

class Solution {
public:
    string countAndSay(int n) {
        vector<int> num;
        num2digit(1, num);

        vector<int> tmp;
        for (int i = 1; i<n; i++) {
            int last = num[0];
            int cur  = last;
            int count= 1;

            for (int i=1; i < num.size(); i++) {
                cur = num[i];
                if (cur != last) {
                    num2digit(count, tmp);
                    tmp.push_back(last);
                    last = cur;
                    count = 1;
                } else {
                    count++;
                }
            }
            
            num2digit(count, tmp);
            tmp.push_back(cur);

            swap(num, tmp);
            tmp.clear();
        }
        string res;
        for (int i=0; i<num.size(); i++) {
            res.push_back((char)(num[i] + 0));
        }
        return res;
    }

    void num2digit(int n, vector<int> &digits) {
        vector<int> res;
        if (n < 0) {
            n = -n;
        }

        do {
            res.push_back(n % 10);
            n /= 10;
        } while (n != 0);

        for (int i=res.size() - 1; i >= 0; i--) {
            digits.push_back(res[i]);
        }
    }
};

LeetCode Count and Say,布布扣,bubuko.com

LeetCode Count and Say

标签:style   blog   color   for   io   div   

原文地址:http://www.cnblogs.com/lailailai/p/3847897.html

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