Skip to main content
Back to problems
#409
Easy Algorithms

Longest palindrome

Hash Table String Greedy
55.8% acceptance
Jan 13, 2026
6347
446
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn longest_palindrome(s: String) -> i32 {
    let mut counts = [0; 128];
    for ch in s.bytes() {
      counts[ch as usize] += 1;
    }
    
    let mut length = 0;
    let mut has_odd = false;
    
    for count in counts.iter() {
      if count % 2 == 0 {
        length += count;
      } else {
        length += count - 1;
        has_odd = true;
      }
    }
    
    if has_odd {
      length + 1
    } else {
      length
    }
  }
}