From 184e456e1b3090d9b26bafef2cd151d49e898672 Mon Sep 17 00:00:00 2001 From: Bauke Date: Sun, 10 Apr 2022 22:41:34 +0200 Subject: [PATCH] Solve word-pattern. --- source/lib.rs | 1 + source/word_pattern/mod.rs | 22 ++++++++++++++++++++++ tests/word_pattern.rs | 16 ++++++++++++++++ 3 files changed, 39 insertions(+) create mode 100644 source/word_pattern/mod.rs create mode 100644 tests/word_pattern.rs diff --git a/source/lib.rs b/source/lib.rs index f1b2545..efcc123 100644 --- a/source/lib.rs +++ b/source/lib.rs @@ -15,3 +15,4 @@ pub mod two_sum; pub mod valid_anagram; pub mod valid_palindrome; pub mod valid_parenthesis; +pub mod word_pattern; diff --git a/source/word_pattern/mod.rs b/source/word_pattern/mod.rs new file mode 100644 index 0000000..1ce3d5b --- /dev/null +++ b/source/word_pattern/mod.rs @@ -0,0 +1,22 @@ +pub fn word_pattern(pattern: String, string: String) -> bool { + let mut key_map = std::collections::HashMap::new(); + let mut value_map = std::collections::HashMap::new(); + + let mut pattern_iter = pattern.chars(); + let mut string_iter = string.split_whitespace(); + + if pattern.len() != string_iter.clone().collect::>().len() { + return false; + } + + for (key, value) in pattern_iter.by_ref().zip(string_iter.by_ref()) { + let expected_value = *key_map.entry(key).or_insert(value); + let expected_key = *value_map.entry(value).or_insert(key); + + if expected_key != key || expected_value != value { + return false; + } + } + + pattern_iter.next().is_none() && string_iter.next().is_none() +} diff --git a/tests/word_pattern.rs b/tests/word_pattern.rs new file mode 100644 index 0000000..d49bd51 --- /dev/null +++ b/tests/word_pattern.rs @@ -0,0 +1,16 @@ +use leetcode::word_pattern::word_pattern; + +use test_case::test_case; + +#[test_case("abba", "dog cat cat dog", true; "example 1")] +#[test_case("abba", "dog cat cat fish", false; "example 2")] +#[test_case("aaaa", "dog cat cat dog", false; "example 3")] +#[test_case("abba", "dog dog dog dog", false; "unique key value pair")] +#[test_case("aaa", "aa aa aa aa", false; "longer string")] +#[test_case("he", "unit", false; "longer pattern")] +fn test_word_pattern(pattern: &str, string: &str, expected: bool) { + assert_eq!( + word_pattern(pattern.to_string(), string.to_string()), + expected + ); +}