Longest Palindrome — LeetCode 409 Python Solution
- Problem
- #409
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. Letters are case sensitive, for example, "Aa" is not considered a palindrome.
Example
- Input
- s = "abccccdd"
- Output
- 7
- Explanation
- One longest palindrome that can be built is "dccaccd", whose length is 7.
Python solution
class Solution:
def longestPalindrome(self, s: str) -> int:
cnt = Counter(s)
ans = sum(v // 2 * 2 for v in cnt.values())
ans += int(ans < len(s))
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n + |\Sigma|) |
| Space | O(|\Sigma|) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 409. Longest Palindrome is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
On a study list
This problem is on Grind 75.
Frequently asked questions
- How hard is LeetCode 409. Longest Palindrome?
- LeetCode 409. Longest Palindrome is rated Easy on LeetCode.
- What is the time complexity of LeetCode 409. Longest Palindrome?
- The Python solution on this page runs in O(n + |\Sigma|).
- What is the space complexity of LeetCode 409. Longest Palindrome?
- The Python solution on this page uses O(|\Sigma|) auxiliary space.
- What topics does LeetCode 409. Longest Palindrome cover?
- LeetCode 409. Longest Palindrome is tagged Greedy, Hash Table and String on LeetCode.