My easy to understand java solution


  • 0
    S
    public String countAndSay(int n) {
            
            String prev_no = "1";
            //traverse till the nth number
            for(int i = 1; i < n; i++){
                //generate current number from its previous number
                char[] s = prev_no.toCharArray();
                //store current number here
                String currNo = "";
                //get first digit from the previous number starting from right
                int p = Integer.parseInt("" + s[0]);
                int count = 1;
                
                //traverse from 2nd till end digit
                for(int j = 1; j < s.length; j++){
                    //if previous digit is same as current
                    if(p == Integer.parseInt("" + s[j]))
                        count++;
                    else{
                        //add the previous digit with its count to current number
                        currNo += Integer.toString(count) + Integer.toString(p);
                        p = Integer.parseInt("" + s[j]);
                        count = 1;
                    }
                }
                //add the final digit and its count to current number
                currNo += Integer.toString(count) + Integer.toString(p);
                //assign previous with this current number
                prev_no = currNo;
            }
            return prev_no;
        }
    '''

Log in to reply
 

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