DevPath

← All problems

Longest Palindrome Length

Easy strings · greedy

Description

Given letters, return the length of the longest palindrome that can be built from them.

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
}

Create a free account to submit solutions, track progress and save problems.

Create account