409. Longest Palindrome
Problem description:
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
2
3
4
5Input:
"abccccdd"
Output:
7
Explanation:
One longest palindrome that can be built is “dccaccd”, whose length is 7.
Solution:
First, count all characters in the string. Even
occurring characters (v[i]%2 == 0) can always be used to build a palindrome. For every odd
occurring character (v[i]%2 == 1), v[i]-1 characters can be used. Result is incremented if there is at least one character with odd occurrence number.
1 | class Solution: |
time complexity: $O(n)$
space complexity: $O(n)$
reference:
related problem: