Java recursive solution easy to understand


  • 0
    H
    public class Solution {
        public String countAndSay(int n) {
            if(n==1) return "1";
            
            String pre=countAndSay(n-1);
            StringBuilder cur=new StringBuilder();
            
            char cur_char=pre.charAt(0); //Current char in exam
            int start=0; //Current char starts...
            
            for(int i=0; i<pre.length(); i++){
                //Update and output
                if(pre.charAt(i)!=cur_char) {
                    cur.append(""+(i-start)+cur_char);
                    cur_char=pre.charAt(i);
                    start=i;
                }
            }
            
            //Last char
            cur.append(""+(pre.length()-start)+cur_char);
            
            return cur.toString();
        }
    }

Log in to reply
 

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