From 3bf98430fc31103ed97ed647a1cf1534381f3dbe Mon Sep 17 00:00:00 2001 From: jackfiled Date: Tue, 7 May 2024 14:18:09 +0800 Subject: [PATCH] 20240507 Finished --- src/problem/mod.rs | 3 +- src/problem/p290_word_pattern.rs | 49 ++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 src/problem/p290_word_pattern.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 002ed57..c7926cc 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -122,4 +122,5 @@ mod p54_spiral_matrix; mod p48_rotate_image; mod p73_set_matrix_zeroes; mod p289_game_of_life; -mod p383_ransom_note; \ No newline at end of file +mod p383_ransom_note; +mod p290_word_pattern; \ No newline at end of file diff --git a/src/problem/p290_word_pattern.rs b/src/problem/p290_word_pattern.rs new file mode 100644 index 0000000..49eb065 --- /dev/null +++ b/src/problem/p290_word_pattern.rs @@ -0,0 +1,49 @@ +/** + * [290] Word Pattern + */ +pub struct Solution {} + + +// submission codes start here +use std::collections::HashMap; + +impl Solution { + pub fn word_pattern(pattern: String, s: String) -> bool { + let words: Vec<&str> = s.split(' ').collect(); + + if words.len() != pattern.len() { + return false; + } + + let mut map = HashMap::new(); + let mut reverse_map = HashMap::new(); + + for (c, word) in pattern.chars().zip(words) { + let entry = map.entry(c).or_insert(word); + + if *entry != word { + return false; + } + + let entry = reverse_map.entry(word).or_insert(c); + + if *entry != c { + return false; + } + } + + true + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_290() { + assert!(Solution::word_pattern("abba".to_owned(), "dog cat cat dog".to_owned())); + } +}