Java solution 3ms, beats 85%...


  • 0
    C
    public String countAndSay(int n) {
       return countAndSayHelper(n, "1"); 
    }
    private String countAndSayHelper(int n, String init){
        if(n == 1){
            return init;
        }
        String next = genNext(init);
        return countAndSayHelper(n-1, next);
    }
    private String genNext(String init){
        StringBuilder str = new StringBuilder();
        int count = 1;
        int i = 0;
        for(; i < init.length() - 1; i++){
            if(init.charAt(i) != init.charAt(i +1)){
                str.append(count);
                str.append(init.charAt(i));
                count = 1;
            }else{
                count++;
            }
        }
        str.append(count);          
        str.append(init.charAt(i)); 
        return str.toString();
    }

Log in to reply
 

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