Concise JavaScript using map


  • 0
    var longestPalindrome = function(s) {
        const counts = {};
        for (let c of s) {
            counts[c] = (counts[c] || 0) + 1;
        }
        let odds = 0;
        for (let c in counts) {
            odds += counts[c] % 2;
        }
        return s.length - odds + !!odds;
    };
    

    And here's a contrived one-liner:

    var longestPalindrome = function(s, o) {
        return s.length - (o = Object.values(s.split('').reduce((c, a) => (c[a] = (c[a] || 0) + 1, c), {})).filter(a => a % 2).length) + !!o;
    };
    

Log in to reply
 

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