Javascript Recursive Solution


  • 0
    A
    /**
     * @param {number} n
     * @return {string}
     */
    var countAndSay = function(n) {
        let result;
        let count = 1;
        const say = function(current) {
            let newCurrent = '';
            if(count === n) {
                result = current;
                console.log(current);
                return;
    
            } else {
                let nums = current.split('');
                let currentNum;
                let currentCount = 0;
                for(let i = 0; i < nums.length; i++) {
                    currentNum = nums[i];
                    currentCount++;
                    if (nums[i+1] !== currentNum) {
                       newCurrent += currentCount;
                        newCurrent += currentNum;
                        currentCount = 0;
                    }
                }
                count++;
                say(newCurrent);
            }
    
        }        
        say('1');
        return result;
    };
    
    

Log in to reply
 

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