Friday, January 9, 2015

Count and Say (LeetCode String)

Question: The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.

Idea: Brute force. Do it exactly as "count" and "say". First initial a counter=1, if string[i]==string[i-1], keep counting; if string[i]!=string[i-1], say counter, then say string[i-1], then reset counter to 1.When the loop is finished, string[last] has not been said, we need to say its counter and string[last] at the end.

Time: O(n) Space: O(1)

Code:
 public class Solution {  
   public String countAndSay(int n) {  
     String start="1";  
     for(int i=1;i<n;i++)  
       start=getNext(start);  
     return start;  
   }  
   public String getNext(String s)  
   {  
     StringBuilder builder=new StringBuilder();  
     int counter=1;  
     for(int i=1;i<s.length();i++)  
     {  
       if(s.charAt(i)==s.charAt(i-1))  
         counter+=1;  
       else  
       {   
         builder.append(counter);  
         builder.append(s.charAt(i-1));  
         counter=1;  
       }  
     }  
     builder.append(counter);  
     builder.append(s.charAt(s.length()-1));  
     return builder.toString();  
   }  
 }  

No comments:

Post a Comment