Skip to content

Commit

Permalink
Add problem 2108: Find First Palindromic String in the Array
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Feb 1, 2024
1 parent d393fe6 commit a0e8751
Show file tree
Hide file tree
Showing 3 changed files with 68 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 @@ -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;
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl Solution {
pub fn first_palindrome(words: Vec<String>) -> 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>) -> String {
Self::first_palindrome(words)
}
}

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

pub trait Solution {
fn first_palindrome(words: Vec<String>) -> String;
}

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

pub fn run<S: Solution>() {
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,
);
}
}
}

0 comments on commit a0e8751

Please sign in to comment.