409. Longest Palindrome
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example “Aa” is not considered a palindrome here.
Note:
Assume the length of given string will not exceed 1,010.
Example:
1 | Input: |
Intuition
A palindorme is a string with letters appear even number of times, plus possibly a unique center letter. For example, in abcba
, letter a
and b
appear two times, and c
is the unique letter.
If we want to build the longest palindorme, it consists of as many partnered letters as possible, plus a possible unique center letter.
Solution I
For each letter accours v
times, if v
is a even number, all of this letter can be partnered, if v
is a odd number, then this letter could be the center letter, in this case, v
can be added to final answers, otherwise, only v - 1
can be added.
The solution is quite simple, we count all the letters in the giving string, then look up the values in the counter, if v
is even, add v
to the final res
, else add v - 1
to res
, set single_num
to 1 indicate that there is a center letter.
1 | class Solution: |
Solution II
Inspire by Discuss, we could simply just count how many letters appear an odd (or even) number of times, because we can use all letters, except for each odd-count letter we must drop one, and if there is a center letter, we can add 1
in at the end.
1-linear solutions:1
2
3# Count odds
def longestPalindrome(self, s: str) -> int:
return len(s) - max(sum(v & 1 for v in collections.Counter.values()) - 1, 0)
1 | # Count evens |
Complexity Analysis
- Time Complexity: O(N), where N is the length of
s
. We need to count each letter. - Space Complexity: O(1), the space for our count, as the alphabet size of s is fixed.