Concise JavaScript using regex


  • 0
    var countAndSay = function(n) {
        let res = '1';
        for (let i = 1; i < n; i++) {
            res = res.replace(/(\d)(?!\1)/g, '$1|').split('|').reduce((res, s) => res + (s ? s.length + s[0] : ''), '');
        }
        return res;
    };
    

    I'll echo the poor problem statement. I originally tried to start at String(n) for n iterations:

    var countAndSay = function(n, i = 1, end = null) {
        return n === 1 || i === end ? '' + n : countAndSay(
            parseInt(
                ('' + n)
                    .replace(/(\d)(?!\1)/g, '$1|')
                    .split('|')
                    .reduce((res, s) => res + (s ? s.length + s[0] : ''), '')
            ),
        i + 1, end || n);
    }
    

Log in to reply
 

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