rustgym/leetcode/
_500_keyboard_row.rs

1struct Solution;
2
3use std::collections::HashMap;
4
5impl Solution {
6    fn find_words(words: Vec<String>) -> Vec<String> {
7        let rows: Vec<String> = [
8            "qwertyuiopQWERTYUIOP",
9            "asdfghjklASDFGHJKL",
10            "zxcvbnmZXCVBNM",
11        ]
12        .iter()
13        .map(|v| (*v).to_string())
14        .collect();
15        let mut hm: HashMap<char, usize> = HashMap::new();
16        for i in 0..3 {
17            let row = &rows[i];
18            for c in row.chars() {
19                hm.insert(c, i);
20            }
21        }
22        let mut res: Vec<String> = vec![];
23        for word in words {
24            let rows: Vec<usize> = word.chars().map(|c| *hm.get(&c).unwrap()).collect();
25            if rows.windows(2).all(|w| w[0] == w[1]) {
26                res.push(word);
27            }
28        }
29        res
30    }
31}
32
33#[test]
34fn test() {
35    let words: Vec<String> = vec_string!["Hello", "Alaska", "Dad", "Peace"];
36    let res: Vec<String> = vec_string!["Alaska", "Dad"];
37    assert_eq!(Solution::find_words(words), res);
38}