首页 > 代码库 > LeetCode "Magical String"

LeetCode "Magical String"

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"