1
Fork 0

Solve keyboard-row.

This commit is contained in:
Bauke 2022-04-11 14:32:59 +02:00
parent c637c55e42
commit e5fb926c91
Signed by: Bauke
GPG Key ID: C1C0F29952BCF558
3 changed files with 43 additions and 0 deletions

View File

@ -0,0 +1,29 @@
pub fn find_words(words: Vec<String>) -> Vec<String> {
// 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<char> {
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
}

View File

@ -6,6 +6,7 @@ pub mod excel_sheet_column_title;
pub mod implement_strstr; pub mod implement_strstr;
pub mod integer_to_roman; pub mod integer_to_roman;
pub mod isomorphic_strings; pub mod isomorphic_strings;
pub mod keyboard_row;
pub mod length_of_last_word; pub mod length_of_last_word;
pub mod longest_common_prefix; pub mod longest_common_prefix;
pub mod missing_number; pub mod missing_number;

13
tests/keyboard_row.rs Normal file
View File

@ -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
);
}