Java easy solution


  • 0
    public class Solution {
        public int magicalString(int n) {
            if (n <= 1) {
                return n;
            }
            int[] magical = new int[n];
            magical[0] = 1;
            int ones = 1;
            int i = 1;
            int j = 1;
            
            while (true) {
                if ((magical[i] = 3 - magical[i - 1]) == 1) {
                    ones++;
                }
                i++;
                if (i == n) {
                    return ones;
                }
           
                if (magical[j] == 2) {
                    if ((magical[i] = magical[i - 1]) == 1) {
                        ones++;
                    }
                    i++;
                    if (i == n) {
                    return ones;
                    }
                }
                j++;
            }
        }
    }

Log in to reply
 

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