My java solution


  • 0
    L
    public class Solution {
        public int magicalString(int n) {
            if(n == 0) return 0;
            if(n <= 3) return 1;
            
            char[] magic = new char[n+1];
            magic[0] = '1';
            magic[1] = '2';
            magic[2] = '2';
            int count = 1, num = 3,index = 2;
            char last = '2';
            
            while(num < n) {
                if(last == '1') last = '2';
                else last = '1';
                
                magic[num++] = last;
                if(magic[index]-'0' == 2) {
                    magic[num++] = last;
                }
                
                if(last == '1') count+=(magic[index]-'0');
                index++;
            }
            
            return magic[n] == '1' ? count-1 : count;
        }
    }
    

Log in to reply
 

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