LeetCode: Longest Palindrome Solution
Trim oddsApproach
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"23occurences4"a": 35"b": 36"c": 37"d": 389number of chars having odd occurence: 41011trim all odd, but keep one12"aa"13"bb"14"cc"15"ddd"1617longest 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).length89 return (10 s.length -11 numberOfCharHavingOddOccurences +12 (numberOfCharHavingOddOccurences > 0)13 )14}
References
Comments
Loading comments...
Tags
leetcode
string
hash table
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
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