|
| 1 | +# 409. Longest Palindrome |
| 2 | + |
| 3 | +## Best Solution |
| 4 | +- Runtime: O(N) |
| 5 | +- Space: O(N) |
| 6 | +- N = Number of characters in string |
| 7 | + |
| 8 | +The question asks for the longest length, not the exact string that needs to be built, this greatly simplifies the question. |
| 9 | +Firstly, think about how a palindrome would be built. |
| 10 | + |
| 11 | +Some questions to ask are: |
| 12 | +1. What character or characters should I choose as the starting middle? |
| 13 | +2. What happens if there are no odd number of characters, just all even? |
| 14 | +3. What happens if there are multiple odd number of characters? |
| 15 | + |
| 16 | +Solution Steps: |
| 17 | +1. Count the occurances of every character in the string via. a dictionary. |
| 18 | +2. Then for each occurance, only count up to the highest even number, both for odd and even occurances. |
| 19 | +3. During this, we keep track if we found an occurance of only one and if we found an odd occurance greater than one. |
| 20 | + |
| 21 | +This only one and greater than one is for when we were selecting the middle character to build the palindrome with. |
| 22 | +If there exists a character that only exists once, that means we can use that as the middle character of the palindrome, all other characters that occur once will be ignored. |
| 23 | +Similarly, if no character that exists once exists, since we only count the highest even occurance for every occurance, we can simply add one to the length if there was an odd occurance greather than one. |
| 24 | + |
| 25 | +``` |
| 26 | +from collections import Counter |
| 27 | +
|
| 28 | +class Solution: |
| 29 | + def longestPalindrome(self, s: str) -> int: |
| 30 | + ch_to_count = Counter(s) |
| 31 | + longest_length = 0 |
| 32 | + only_one = greater_than_one = False |
| 33 | + for count in ch_to_count.values(): |
| 34 | + if count % 2 == 0: # even |
| 35 | + longest_length += count |
| 36 | + else: # odd |
| 37 | + if count == 1: |
| 38 | + only_one = True |
| 39 | + else: |
| 40 | + greater_than_one = True |
| 41 | + longest_length += count-1 |
| 42 | + if only_one: |
| 43 | + longest_length += 1 |
| 44 | + elif greater_than_one: |
| 45 | + longest_length += 1 |
| 46 | + return longest_length |
| 47 | +``` |
0 commit comments