Short Java Solution uses Queue


  • 0
    F

    very simple steps:

    1. poll from the Queue to get the next added number count

    2. put the new number into the Queue

      public int magicalString(int n) {
      if(n<=0) return 0;
      // initialize queue with the third number 2
      Queue <Integer> q = new LinkedList<> ();
      q.add(2);

       // start when n > 3 
       int cnt = 3;
       int num = 1;
       int result = 1;
       
       while(cnt < n) {
           int newNumCnt = q.poll();
           for (int i = 0; i<newNumCnt && cnt < n ;i++) {
               q.add(num);
               cnt ++;
               result += num == 1 ? 1 : 0;
           }
           num = num ^ 3;
       }
       return result;
      

      }


Log in to reply
 

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