|
| 1 | +pub struct Solution {} |
| 2 | + |
| 3 | +impl Solution { |
| 4 | + fn get_pattern(s: &str) -> Vec<Vec<usize>> { |
| 5 | + let mut pattern = vec![vec![]; 26]; |
| 6 | + for (i, c) in s.char_indices() { |
| 7 | + pattern[c as usize - 'a' as usize].push(i); |
| 8 | + } |
| 9 | + pattern.sort(); |
| 10 | + pattern.into_iter().filter(|x| x.len() > 0).collect() |
| 11 | + } |
| 12 | + |
| 13 | + pub fn find_and_replace_pattern(words: Vec<String>, pattern: String) -> Vec<String> { |
| 14 | + let p = Self::get_pattern(&pattern); |
| 15 | + words |
| 16 | + .into_iter() |
| 17 | + .filter(|w| Self::get_pattern(w) == p) |
| 18 | + .collect() |
| 19 | + } |
| 20 | +} |
| 21 | + |
1 | 22 | #[cfg(test)]
|
2 |
| -mod tests { |
| 23 | +mod test { |
| 24 | + use super::*; |
| 25 | + |
| 26 | + fn matches(words: Vec<&str>, pattern: &str, expected: Vec<&str>) { |
| 27 | + assert_eq!( |
| 28 | + Solution::find_and_replace_pattern( |
| 29 | + words.iter().map(|x| x.to_string()).collect(), |
| 30 | + pattern.to_string(), |
| 31 | + ), |
| 32 | + expected |
| 33 | + .iter() |
| 34 | + .map(|x| x.to_string()) |
| 35 | + .collect::<Vec<String>>() |
| 36 | + ) |
| 37 | + } |
| 38 | + |
| 39 | + #[test] |
| 40 | + fn example_1() { |
| 41 | + let words = vec!["abc", "deq", "mee", "aqq", "dkd", "ccc"]; |
| 42 | + let pattern = "abb"; |
| 43 | + let expected = vec!["mee", "aqq"]; |
| 44 | + matches(words, pattern, expected); |
| 45 | + } |
| 46 | + |
3 | 47 | #[test]
|
4 |
| - fn it_works() { |
5 |
| - assert_eq!(2 + 2, 4); |
| 48 | + fn example_2() { |
| 49 | + let words = vec!["a", "b", "c"]; |
| 50 | + let pattern = "a"; |
| 51 | + let expected = vec!["a", "b", "c"]; |
| 52 | + matches(words, pattern, expected); |
6 | 53 | }
|
7 | 54 | }
|
0 commit comments