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

LeetCode "Magical String"

时间:2017-01-14 14:52:42      阅读:279      评论:0      收藏:0      [点我收藏+]

标签:++   ica   length   int   leetcode   false   move   bool   can   

Fun one. A matter of string generation by given rules. I know it can be much shorter.. but i‘m lazy to do that.

class Solution {
public:
    int magicalString(int n) {
        if(!n) return 0;
        if(n < 2) return 1;
        
        int ret = 1;
        string s = "1";
        bool isOne = false;
        int i = 0; // num inx
        while(s.length() < n)
        {
            int cnt = 0;
            if(isOne)
            {
                s += 1; ret ++;
                cnt = (s[++i] - 1) + 1;
                if(cnt == 2 && n > s.length())
                {s += 1; ret ++;}
            }
            else
            {
                s += 2;
                cnt = (s[++i] - 1) + 1;
                if(cnt == 2) s += 2;
            }
            
            // move on
            isOne = !isOne;
        }
        
        return ret;
    }
};

LeetCode "Magical String"

标签:++   ica   length   int   leetcode   false   move   bool   can   

原文地址:http://www.cnblogs.com/tonix/p/6285227.html

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