Skip to content

Commit

Permalink
Add problem 0500: Keyboard Row
Browse files Browse the repository at this point in the history
  • Loading branch information
Spxg committed Jun 9, 2024
1 parent 111edc5 commit 6ebab6c
Show file tree
Hide file tree
Showing 3 changed files with 69 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 @@ -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;
Expand Down
40 changes: 40 additions & 0 deletions src/problem_0500_keyboard_row/iterative.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
pub struct Solution;

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

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

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

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

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

0 comments on commit 6ebab6c

Please sign in to comment.