diff --git a/README.md b/README.md index 0360e00..62492c1 100644 --- a/README.md +++ b/README.md @@ -169,6 +169,7 @@ programming challenges completed in other languages. - [Count Negative Numbers](https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix) - [Guess Number](https://leetcode.com/problems/guess-number-higher-or-lower/) - [Ransom Note](https://leetcode.com/problems/ransom-note) +- [Word Pattern](https://leetcode.com/problems/word-pattern) #### Medium diff --git a/src/leetcode/mod.rs b/src/leetcode/mod.rs index dcad05a..cbfc78d 100644 --- a/src/leetcode/mod.rs +++ b/src/leetcode/mod.rs @@ -157,6 +157,7 @@ mod unguarded_cells; mod unique_occurrences; mod valid_parenthesis; mod valid_sudoku; +mod word_pattern; mod x_kind; mod xor_subarray; mod zero_or_one; diff --git a/src/leetcode/word_pattern.rs b/src/leetcode/word_pattern.rs new file mode 100644 index 0000000..1346671 --- /dev/null +++ b/src/leetcode/word_pattern.rs @@ -0,0 +1,37 @@ +use std::collections::HashMap; + +pub fn word_pattern(pattern: String, s: String) -> bool { + let words: Vec<_> = s.split_whitespace().map(String::from).collect(); + if pattern.len() != words.len() { + return false; + } + + let pattern = pattern.as_bytes(); + let mut map = HashMap::new(); + for (i, word) in words.into_iter().enumerate() { + if map.insert(pattern[i].to_string(), i) != map.insert(word, i) { + return false; + } + } + true +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test() { + assert!(word_pattern("aaa".to_string(), "dog dog dog".to_string())) + } + + #[test] + fn test_name() { + assert!(!word_pattern("aaa".to_string(), "dog cat dog".to_string())); + assert!(!word_pattern( + "abba".to_string(), + "dog dog dog dog".to_string() + )); + assert!(!word_pattern("aaa".to_string(), "aa aa aa aa".to_string())) + } +}