Brute-Force Java Solution


  • 0
    O
    public class Solution {
        public String countAndSay(int n) {
          
            if(n == 1) return "1";        
            StringBuilder sb = new StringBuilder("1");        
            while(n > 1){            
                    int counter = 1;
                    StringBuilder temp = new StringBuilder();
                    for(int i =1; i < sb.length(); i ++){
                     if(sb.charAt(i-1) == sb.charAt(i)){
                         counter ++;
                     } else {
                         temp.append(Integer.toString(counter));
                         temp.append(sb.charAt(i -1));
                         counter = 1;
                     }  
                    }
                temp.append(counter);
                temp.append(sb.charAt(sb.length()-1));
                sb = temp;
                n --;
            }
            return sb.toString();
            
        }
    }
    
    

Log in to reply
 

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