Longest Palindrome From Char Counts
Count characters into a HashMap entry map, add every complete pair to the palindrome length, and reserve one leftover odd character for the center.
Code
use std::collections::HashMap;
fn main() {
let letters = "bananas";
let mut counts: HashMap<char, usize> = HashMap::new();
for ch in letters.chars() {
*counts.entry(ch).or_insert(0) += 1;
}
// longest palindrome from char counts: pairs go both sides, one odd char centers
let mut length = 0;
let mut odd = 0;
for count in counts.values() {
length += count / 2 * 2;
if count % 2 == 1 {
odd += 1;
}
}
if odd > 0 {
length += 1;
}
println!("longest palindrome length: {length}");
}Longest Palindrome From Char Counts: what runs and why
Longest Palindrome From Char Counts is built around the function main.
The file repeats itself only inside for ch in letters.chars().
Watch out for
- Import surface, if any, is limited to standard-library modules.
Using it
The shape of the callable: fn main()
The run emits 1 labeled section — longest palindrome length: — one per step.
Key statements
length += count / 2 * 2;
length += 1;
Interactive Tools for This Topic
FAQ
- What does Longest Palindrome From Char Counts print when run?
- The script runs standalone; its 1 labeled outputs include `longest palindrome length:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.