C++ Solution using Queue


  • 0
    int magicalString(int n) {
            queue<int> q;
            q.push(2);
            int res = 1;
            for(int i=2; i<n; ++i)
            {
                int repeat = q.front();
                q.pop();
                if(repeat==1) res++;
                int input = (q.back()==2) ? 1 : 2;
                for(int j=0; j<repeat; ++j)
                    q.push(input);
            }
            return (n==0) ? 0 : res;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.