diff --git a/src/lib.rs b/src/lib.rs index 209157d5..6411fce3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1435,6 +1435,7 @@ pub mod problem_2091_removing_minimum_and_maximum_from_array; pub mod problem_2095_delete_the_middle_node_of_a_linked_list; pub mod problem_2099_find_subsequence_of_length_k_with_the_largest_sum; pub mod problem_2103_rings_and_rods; +pub mod problem_2108_find_first_palindromic_string_in_the_array; #[cfg(test)] mod test_utilities; diff --git a/src/problem_2108_find_first_palindromic_string_in_the_array/iterative.rs b/src/problem_2108_find_first_palindromic_string_in_the_array/iterative.rs new file mode 100644 index 00000000..f6017093 --- /dev/null +++ b/src/problem_2108_find_first_palindromic_string_in_the_array/iterative.rs @@ -0,0 +1,42 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl Solution { + pub fn first_palindrome(words: Vec) -> String { + words + .into_iter() + .find(|word| { + let mut iter = word.bytes(); + + while let Some(lhs) = iter.next() { + if let Some(rhs) = iter.next_back() { + if lhs != rhs { + return false; + } + } else { + break; + } + } + + true + }) + .unwrap_or_default() + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn first_palindrome(words: Vec) -> String { + Self::first_palindrome(words) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_2108_find_first_palindromic_string_in_the_array/mod.rs b/src/problem_2108_find_first_palindromic_string_in_the_array/mod.rs new file mode 100644 index 00000000..506d1f50 --- /dev/null +++ b/src/problem_2108_find_first_palindromic_string_in_the_array/mod.rs @@ -0,0 +1,25 @@ +pub mod iterative; + +pub trait Solution { + fn first_palindrome(words: Vec) -> String; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [ + (&["abc", "car", "ada", "racecar", "cool"] as &[_], "ada"), + (&["notapalindrome", "racecar"], "racecar"), + (&["def", "ghi"], ""), + ]; + + for (words, expected) in test_cases { + assert_eq!( + S::first_palindrome(words.iter().copied().map(str::to_string).collect()), + expected, + ); + } + } +}