diff --git a/src/lib.rs b/src/lib.rs index 7a0f920..8f95e4c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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; diff --git a/src/problem_0409_longest_palindrome/iterative.rs b/src/problem_0409_longest_palindrome/iterative.rs new file mode 100644 index 0000000..fb4716e --- /dev/null +++ b/src/problem_0409_longest_palindrome/iterative.rs @@ -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::(); + } +} diff --git a/src/problem_0409_longest_palindrome/mod.rs b/src/problem_0409_longest_palindrome/mod.rs new file mode 100644 index 0000000..8ec4fc5 --- /dev/null +++ b/src/problem_0409_longest_palindrome/mod.rs @@ -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() { + let test_cases = [("abccccdd", 7), ("a", 1), ("bb", 2)]; + + for (s, expected) in test_cases { + assert_eq!(S::longest_palindrome(s.to_string()), expected); + } + } +}