# LeetCode: Longest Palindrome Solution

Trim odds

## Approach

Count occurence of each character

Trim all odd to even, but make sure that to keep one, since it's ok to have a char that have odd number of occurence in the palindrome

Example

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}s = "aaabbbcccddd"2
3occurences4"a": 35"b": 36"c": 37"d": 38
9number of chars having odd occurence: 410
11trim all odd, but keep one12"aa"13"bb"14"cc"15"ddd"16
17longest palindrome: "abcdddcba" -> length of 11```

## Implementation

```1var longestPalindrome = function (s) {2  const charOccurences = s3    .split("")4    .reduce((acc, char) => acc.set(char, (acc.get(char) || 0) + 1), new Map())5  const numberOfCharHavingOddOccurences = Array.from(6    charOccurences.values()7  ).filter(occurences => occurences % 2 !== 0).length8
9  return (10    s.length -11    numberOfCharHavingOddOccurences +12    (numberOfCharHavingOddOccurences > 0)13  )14}```

Original problem

leetcode

string

hash table

## Next Post

LeetCode: Validate Binary Search Tree

Aug 20, 2022

Traverse in-order and validate the traversed result

## Previous Post

LeetCode: Counting Bits

Aug 15, 2022

Convert to binary with toString() method

Search Posts