DEV Community

Discussion on: Leetcode Daily - Longest Palindrome

Collapse
 
vidit1999 profile image
Vidit Sarkar

Thanks for sharing the problem and your solution. Here is my approach.

var longestPalindrome = function(s) {
    /*
    1. We only need the length of the longest palindrome.
    2. Store all character with its corresponding count in dict.
    3. All characaters that appears even number of times will be part
       of palindrome, so add their count to all_even_count.
    4. Palindrome can contain only one character that occurs odd
       number of time. So for the size to be maximum get the odd character
       that appears max number of times and store it's occurence count in max_odd_count.
    5. Return (all_even_count + max_odd_count).
    */
    const dict = {}

    for (let i = 0; i < s.length; i++) {
        if (dict[s[i]]) {
            dict[s[i]] += 1
        } else {
            dict[s[i]] = 1
        }
    }

    let all_even_count = 0, max_odd_count = 0

    for(var key in dict) {
        if(dict[key]%2 === 0) {
            all_even_count += dict[key]
        } else {
            max_odd_count = Math.max(max_odd_count, dict[key])
        }
    }

    return all_even_count + max_odd_count;
};