Skip to content

Commit

Permalink
Add problem 0409: Longest Palindrome
Browse files Browse the repository at this point in the history
  • Loading branch information
Spxg committed Jun 2, 2024
1 parent 37b2b0d commit 0e7445d
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,7 @@ pub mod problem_0398_random_pick_index;
pub mod problem_0400_nth_digit;
pub mod problem_0404_sum_of_left_leaves;
pub mod problem_0405_convert_a_number_to_hexadecimal;
pub mod problem_0409_longest_palindrome;
pub mod problem_0412_fizz_buzz;
pub mod problem_0413_arithmetic_slices;
pub mod problem_0415_add_strings;
Expand Down
27 changes: 27 additions & 0 deletions src/problem_0409_longest_palindrome/iterative.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
pub struct Solution;

impl Solution {
pub fn longest_palindrome(s: String) -> i32 {
let mut chs = [0; 128];
s.bytes().for_each(|x| chs[x as usize] += 1);

let result = chs
.into_iter()
.fold(0, |acc, count| acc + (count - count % 2));
result + i32::from(result as usize != s.len())
}
}

impl super::Solution for Solution {
fn longest_palindrome(s: String) -> i32 {
Self::longest_palindrome(s)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
18 changes: 18 additions & 0 deletions src/problem_0409_longest_palindrome/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
pub mod iterative;

pub trait Solution {
fn longest_palindrome(s: String) -> i32;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
let test_cases = [("abccccdd", 7), ("a", 1), ("bb", 2)];

for (s, expected) in test_cases {
assert_eq!(S::longest_palindrome(s.to_string()), expected);
}
}
}

0 comments on commit 0e7445d

Please sign in to comment.