Share my queue solution


  • 0
    S
    public int magicalString(int n) {
    	if (n == 0) return 0;
    	if (n < 4) return 1;
    	Queue<Integer> queue = new LinkedList<>();
    	int count = 1, cur = 2;
    	boolean tailIsOne = false;
    	while (n > 3) {
    		if (cur == 1){
    			n--;
    			if (tailIsOne) queue.offer(2);
    			else {
    				queue.offer(1);
    				count++;
    			}
    		}else{
    			n -= 2;
    			if (tailIsOne) {
    				queue.offer(2);
    				queue.offer(2);
    			}
    			else {
    				queue.offer(1);
    				queue.offer(1);
    				count += 2;
    			}
    		}
    		cur = queue.poll();
    		tailIsOne = !tailIsOne;
    	} 
    	return n == 3 ? count : tailIsOne ? count-1 : count;
    }
    

Log in to reply
 

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