Ac solution code


  • 0

    This game is to count the frequency for each unique digit from left to right.

    And the sequences of the output are in the fixed order: 1, 11, 21, 1211, 111221, ...

    sequence[1] = 1;
    sequence[2] = 11;
    sequence[3] = 21;
    sequence[4] = 1211;
    sequence[5] = 111221;
    

    We just need to find sequence[n].

    JAVA Code:

     public String countAndSay(int n) {		 
    	 String prev = "1"; // Always starts from "1", as the game rule: 1, 11, 21, 1211, 111221, ...			
    	 for (int i = 1; i < n ; i++) {
    		 char last = ' ';
    		 int count = 1;	
    		 String sequence ="";
    		 for (int j = 0; j < prev.length(); j++) {
    			 char cur = prev.charAt(j);
    			 if (cur == last)
    				 count++;
    			 else { 
    				 if (last != ' ')
    					 sequence += String.format("%d%c", count, last);
    				 last = cur;
    				 count = 1;
    			 }				 			 
    		 }
    		 if (last != ' ') {
    			 sequence += String.format("%d%c", count, last);
    	        prev = sequence;
    		 }
    	 }
    	 return prev;
     }

Log in to reply
 

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