Solve keyboard-row.
This commit is contained in:
parent
c637c55e42
commit
e5fb926c91
|
@ -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
|
||||||
|
}
|
|
@ -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;
|
||||||
|
|
|
@ -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
|
||||||
|
);
|
||||||
|
}
|
Loading…
Reference in New Issue