Java accepted 5 ms recursive solution


  • 0
    Y
    public String countAndSay(int n) {
            if(n <= 1){
                return "1";
            }
            
            String s = countAndSay(n - 1);
            
            StringBuilder answer = new StringBuilder();
            int counter = 1; 
            for(int i = 1, len = s.length(); i < len; i++){
                char prev = s.charAt(i - 1);
                if(s.charAt(i) == prev){
                    counter++;
                }else{
                    answer.append(counter).append(prev);
                    counter = 1;
                }
            }
            answer.append(counter).append(s.charAt(s.length() - 1));
            return answer.toString();
        }
    

  • 0
    Y

    @ylychko Please, ignore '5ms' indicated in header, it really depends on target n


Log in to reply
 

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