diff --git a/src/lib.rs b/src/lib.rs index 28e8183..d7c9123 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -345,6 +345,7 @@ pub mod problem_0481_magical_string; pub mod problem_0482_license_key_formatting; pub mod problem_0485_max_consecutive_ones; pub mod problem_0498_diagonal_traverse; +pub mod problem_0500_keyboard_row; pub mod problem_0503_next_greater_element_ii; pub mod problem_0507_perfect_number; pub mod problem_0513_find_bottom_left_tree_value; diff --git a/src/problem_0500_keyboard_row/iterative.rs b/src/problem_0500_keyboard_row/iterative.rs new file mode 100644 index 0000000..5759b09 --- /dev/null +++ b/src/problem_0500_keyboard_row/iterative.rs @@ -0,0 +1,40 @@ +pub struct Solution; + +impl Solution { + pub fn find_words(words: Vec) -> Vec { + let mut chs = [0; 128]; + let mut result = Vec::with_capacity(words.len()); + for (idx, row) in [ + "qwertyuiopQWERTYUIOP", + "asdfghjklASDFGHJKL", + "zxcvbnmZXCVBNM", + ] + .into_iter() + .enumerate() + { + row.bytes().for_each(|x| chs[x as usize] = idx); + } + for word in words { + let mut iter = word.bytes(); + let row = chs[iter.next().unwrap() as usize]; + if iter.all(|x| chs[x as usize] == row) { + result.push(word); + } + } + result + } +} + +impl super::Solution for Solution { + fn find_words(words: Vec) -> Vec { + Self::find_words(words) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_0500_keyboard_row/mod.rs b/src/problem_0500_keyboard_row/mod.rs new file mode 100644 index 0000000..70dcfe3 --- /dev/null +++ b/src/problem_0500_keyboard_row/mod.rs @@ -0,0 +1,28 @@ +pub mod iterative; + +pub trait Solution { + fn find_words(words: Vec) -> Vec; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [ + ( + &["Hello", "Alaska", "Dad", "Peace"] as &[_], + &["Alaska", "Dad"] as &[_], + ), + (&["omk"], &[]), + (&["adsdf", "sfd"], &["adsdf", "sfd"]), + ]; + + for (words, expected) in test_cases { + assert_eq!( + S::find_words(words.iter().copied().map(str::to_string).collect()), + expected + ); + } + } +}