Recursive solution in java


  • 0
    R

    public String countAndSay(int n) {

        if(n==1) return "" + 1;
        String sn = countAndSay(n-1);
        
        StringBuilder sb = new StringBuilder();
        
        char pc = sn.charAt(0);
        int count = 1;
        for(int i=1; i<sn.length(); i++){
            char c = sn.charAt(i);
            if(c == pc) count++;
            else{
                sb.append(count + "" + pc);
                pc = c;
                count = 1;
            }
        }
        
        sb.append(count + "" + pc);
        
        
        
        String ans = sb.toString();
        
        return ans;
        
    }

Log in to reply
 

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