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

1s = "aaabbbcccddd"
2
3occurences
4"a": 3
5"b": 3
6"c": 3
7"d": 3
8
9number of chars having odd occurence: 4
10
11trim all odd, but keep one
12"aa"
13"bb"
14"cc"
15"ddd"
16
17longest palindrome: "abcdddcba" -> length of 11

Implementation

1var longestPalindrome = function (s) {
2 const charOccurences = s
3 .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).length
8
9 return (
10 s.length -
11 numberOfCharHavingOddOccurences +
12 (numberOfCharHavingOddOccurences > 0)
13 )
14}

References

Original problem

Comments

Loading comments...

Tags

leetcode

string

hash table

Next Post

LeetCode: Validate Binary Search Tree

Traverse in-order and validate the traversed result

Previous Post

LeetCode: Counting Bits

Convert to binary with toString() method

HoningJS

Search Posts