Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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;
    }
};
posted on 2017-01-14 13:50  Tonix  阅读(142)  评论(0编辑  收藏  举报