Longest Palindrome Length
Easy strings · greedy
Description
Constraints
1 <= length <= 2000
Examples
Input: s = "abccccdd"
Output: 7
Hints (1)
- Every even character count contributes fully; one odd character can sit in the middle.
Solutions
Count pairs plus one odd centre. · Time O(n) · Space O(1)
func longestPalindromeLength(s string) int {
count := map[byte]int{}
for i := 0; i < len(s); i++ {
count[s[i]]++
}
length := 0
odd := false
for _, c := range count {
length += (c / 2) * 2
if c%2 == 1 {
odd = true
}
}
if odd {
length++
}
return length
}
Count pairs plus one odd centre. · Time O(n) · Space O(1)
function longestPalindromeLength(s) {
const count = {};
for (const c of s) count[c] = (count[c] || 0) + 1;
let length = 0, odd = false;
for (const c of Object.values(count)) { length += Math.floor(c / 2) * 2; if (c % 2) odd = true; }
return length + (odd ? 1 : 0);
}
Count pairs plus one odd centre. · Time O(n) · Space O(1)
function longestPalindromeLength($s) {
$count = [];
for ($i = 0; $i < strlen($s); $i++) { $count[$s[$i]] = ($count[$s[$i]] ?? 0) + 1; }
$length = 0; $odd = false;
foreach ($count as $c) { $length += intdiv($c, 2) * 2; if ($c % 2 === 1) { $odd = true; } }
return $length + ($odd ? 1 : 0);
}
Count pairs plus one odd centre. · Time O(n) · Space O(1)
def longestPalindromeLength(s):
from collections import Counter
length = 0
odd = False
for c in Counter(s).values():
length += (c // 2) * 2
if c % 2:
odd = True
return length + (1 if odd else 0)
Count pairs plus one odd centre. · Time O(n) · Space O(1)
function longestPalindromeLength(s: string): number {
const count: Record<string, number> = {};
for (const c of s) count[c] = (count[c] || 0) + 1;
let length = 0, odd = false;
for (const c of Object.values(count)) { length += Math.floor(c / 2) * 2; if (c % 2) odd = true; }
return length + (odd ? 1 : 0);
}
Create a free account to submit solutions, track progress and save problems.
Create account