Recursive JS solution


  • 0
    var countAndSay = function(n) {
        if (n === 0) return '';
        if (n === 1) return '1';
        const t = countAndSay(n - 1);
        let s = '';
        let stack = [t[0]];
        for (let i = 1; i < t.length; i++) {
            if (t[i] === stack[stack.length - 1]) {
                stack.push(t[i]);
            } else {
                s += stack.length;
                s += stack[0];
                stack = [t[i]];
            }
        }
        if (stack.length > 0) {
            s += stack.length;
            s += stack[0];
        }
        return s;
    };
    

Log in to reply
 

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