My java code with comments


  • 0
    T

    Go on building new strings for n = 2,3... from previous, with base case as 1 = "1".

    public class Solution {
        public String countAndSay(int n) {
            if(n < 1)
                return "";
            
            StringBuilder res = new StringBuilder();
            //loop starts with 2--appending base case 1 to res
            res.append("1");
            for(int i = 2; i <= n; i++) {
                //read res, form a new string sb
                StringBuilder sb = new StringBuilder();
                
                //counter and previous number to keep track
                int ct = 0, num = -1;
                for(int j = 0; j < res.length(); j++) {
                    //get current char integer
                    int k = Character.getNumericValue(res.charAt(j));
                    if(num == -1)//if num is not initialized--init num
                        num = k;
                    else if(num != k) {//if num is diff than current--append ct and num to sb
                        sb.append(ct + "" + num);
                        num = k;
                        ct = 0;
                    }
                    ct++;
                }
                sb.append(ct + "" + num);
                res = sb;
            }
            
            return res.toString();
        }
    }
    

Log in to reply
 

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