Simple java solution


  • 0
    S
    class MagicalStringSolution {
        public int magicalString(int n) {
            if (n <= 0) return 0;
            if (n == 1 || n == 2) return 1;
    
            int sum = 1;
            StringBuilder s1 = new StringBuilder("12");
    
            int index = 1;
            int count = 1;
            char curr = '2';
    
            while (index < n) {
                if (s1.charAt(index) == '1') sum++;
    
                while (count < s1.charAt(index) - '0') {
                    s1.append(curr);
                    count++;
                }
    
                count = 0;
                if (curr == '1') curr = '2';
                else curr = '1';
                index++;
            }
    
            return sum;
        }
    }

Log in to reply
 

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