My Java Recursive Solution 6ms


  • 0
    E
    public class Solution {
        public String countAndSay(int n) {
            if(n==1)return "1";
            return counter(2,n,"11");
        }
        
        String counter(int level,int max,String d){
            if(level>=max){
                return d;
            }else{
                return counter(level+1,max,helper(d));
            }
        }
        
        String helper(String d){
            StringBuilder sb = new StringBuilder();
            int count = 1;
            char current = d.charAt(0);
            for(int k=1;k<d.length();k++){
                if(current!=d.charAt(k)){
                    sb.append(count);
                    sb.append(current);
                    count = 1;
                    current = d.charAt(k);
                }else{
                    count++;
                }
            }
            sb.append(count);
            sb.append(current);
    
            return sb.toString();
        }
    }
    

Log in to reply
 

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