Java recursive


  • 0
    D
    class Solution {
        public String countAndSay(int n) {
            return countAndSayHelper("1",1,n);
        }
        public String countAndSayHelper(String s,int k,int n){
            if(k==n) return s;
            int c=1;
            char prev=s.charAt(0);
            int l=s.length();
            StringBuilder str=new StringBuilder();
            int i=1;
            while(i<l){
                if(s.charAt(i)==prev){
                    c++;
                }
                else{
                    str.append(c).append(prev);
                    prev=s.charAt(i);
                    c=1;
                }
                i++;
            }
            str.append(c).append(prev);
            return countAndSayHelper(str.toString(),++k,n);
        }
    }
    

Log in to reply
 

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