From e5fb926c91395c62fd067c0a3b50e1b677b603aa Mon Sep 17 00:00:00 2001 From: Bauke Date: Mon, 11 Apr 2022 14:32:59 +0200 Subject: [PATCH] Solve keyboard-row. --- source/keyboard_row/mod.rs | 29 +++++++++++++++++++++++++++++ source/lib.rs | 1 + tests/keyboard_row.rs | 13 +++++++++++++ 3 files changed, 43 insertions(+) create mode 100644 source/keyboard_row/mod.rs create mode 100644 tests/keyboard_row.rs diff --git a/source/keyboard_row/mod.rs b/source/keyboard_row/mod.rs new file mode 100644 index 0000000..38d26e0 --- /dev/null +++ b/source/keyboard_row/mod.rs @@ -0,0 +1,29 @@ +pub fn find_words(words: Vec) -> Vec { + // Uncomment FromIterator in Leetcode since they're using Rust Edition 2018. + // Edition 2021 has this trait in its prelude. + + // use std::iter::FromIterator; + use std::collections::HashSet; + + fn hashset_from_str(string: &str) -> HashSet { + std::collections::HashSet::<_>::from_iter(string.to_lowercase().chars()) + } + + let rows = [ + hashset_from_str("qwertyuiop"), + hashset_from_str("asdfghjkl"), + hashset_from_str("zxcvbnm"), + ]; + + let mut result = vec![]; + + for word in words { + let word_set = hashset_from_str(&word); + + if rows.iter().any(|row| word_set.is_subset(row)) { + result.push(word); + } + } + + result +} diff --git a/source/lib.rs b/source/lib.rs index 7ad9cc0..7dd3558 100644 --- a/source/lib.rs +++ b/source/lib.rs @@ -6,6 +6,7 @@ pub mod excel_sheet_column_title; pub mod implement_strstr; pub mod integer_to_roman; pub mod isomorphic_strings; +pub mod keyboard_row; pub mod length_of_last_word; pub mod longest_common_prefix; pub mod missing_number; diff --git a/tests/keyboard_row.rs b/tests/keyboard_row.rs new file mode 100644 index 0000000..229545a --- /dev/null +++ b/tests/keyboard_row.rs @@ -0,0 +1,13 @@ +use leetcode::keyboard_row::find_words; + +use test_case::test_case; + +#[test_case(&["Hello", "Alaska", "Dad", "Peace"], &["Alaska", "Dad"]; "example 1")] +#[test_case(&["omk"], &[]; "example 2")] +#[test_case(&["adsdf", "sfd"], &["adsdf", "sfd"]; "example 3")] +fn test_keyboard_row(input: &[&str], expected: &[&str]) { + assert_eq!( + find_words(input.iter().map(ToString::to_string).collect()), + expected + ); +}