Easy-Understanding JAVA solution using recursive


  • 0
    S
    public class Solution {
        public String countAndSay(int n) {
            return solve("1",n);
            
        }
        String solve(String input,int n){
            if(n>1){
            StringBuilder sb=new StringBuilder();
            char cur=input.charAt(0);
            int count=1;
            for(int i=1;i<input.length();i++){
                if(input.charAt(i)==cur)count++;
                else{
                    sb.append(count).append(cur);
                    cur=input.charAt(i);
                    count=1;
                }
            }
            sb.append(count).append(cur);
            String res=sb.toString();
            n-=1;
             input=solve(res,n);
            }
            return input;
        }
    }
    

Log in to reply
 

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