Javascript solution using hash table


  • 0
    Z
    var longestPalindrome = function(s) {
        let hash = {};
        
        for (let i = 0; i < s.length; i++) {
            let char = s.charAt(i);
            if (hash.hasOwnProperty(char)) {
                hash[char] += 1;
            } else {
                hash[char] = 1;
            }
        }
        
        let odd = 0;
        Object.keys(hash).forEach(char => {
            if (hash[char] % 2) {
                odd += 1;
            }
        });
        
        // If there are letters that appear odd number of times, we can only
        // use the letters (count - 1) number of times, EXCEPT one odd letter in
        // the middle of the palindrome
        return odd ? s.length - odd + 1 : s.length;
    };
    

Log in to reply
 

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