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())); + } +}