The Longest Palindrome solutions are below.
15 Jun 2024•Easy•C++ / Python / TypeScript
Longest Palindrome
C++, Python and TypeScript solutions for Longest Palindrome.
Solution files
Python•longest-palindrome/synced-solution.py
def longestPalindrome(s):
from collections import Counter
char_count = Counter(s)
length = 0
has_odd = False
for count in char_count.values():
length += (count // 2) * 2
if count % 2 == 1:
has_odd = True
return length + (1 if has_odd else 0)
C++•longest-palindrome/synced-solution.cpp
class Solution {
public:
int longestPalindrome(string s) {
unordered_map<char, int> count;
for (char c : s) {
count[c]++;
}
int length = 0;
bool has_odd = false;
for (auto& p : count) {
length += (p.second / 2) * 2;
if (p.second % 2 == 1) {
has_odd = true;
}
}
return length + (has_odd ? 1 : 0);
}
};
TypeScript•longest-palindrome/synced-solution.ts
function longestPalindrome(s: string): number {
const count = new Map<string, number>();
for (const char of s) {
count.set(char, (count.get(char) || 0) + 1);
}
let length = 0;
let hasOdd = false;
for (const cnt of count.values()) {
length += Math.floor(cnt / 2) * 2;
if (cnt % 2 === 1) {
hasOdd = true;
}
}
return length + (hasOdd ? 1 : 0);
}