Java solution handles special case


  • 0
    S
        public int magicalString(int n) {
            if (n < 1)
                return 0;
            if (n < 4)
                return 1;
                
            int[] arr = new int[n+2];
            int count = 0;
            arr[1] = 1;
            arr[2] = 2;arr[3] = 2;
            int cur1 = 3, cur2 = 4, i;
            
            while (cur2 <= n) {
                if (arr[cur1] == 1) {
                    arr[cur2] = 3 - arr[cur2-1];
                    cur2++;
                } else {
                    arr[cur2+1] = arr[cur2] = 3 - arr[cur2-1];
                    cur2 += 2;
                }
                cur1++;
            }
            for (i=1;i<=n;i++)
                if (arr[i] == 1) {
                    count++;
                }
            return count;
        }
    }

Log in to reply
 

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