1
Fork 0

Solve word-pattern.

This commit is contained in:
Bauke 2022-04-10 22:41:34 +02:00
parent 2847166137
commit 184e456e1b
Signed by: Bauke
GPG Key ID: C1C0F29952BCF558
3 changed files with 39 additions and 0 deletions

View File

@ -15,3 +15,4 @@ pub mod two_sum;
pub mod valid_anagram;
pub mod valid_palindrome;
pub mod valid_parenthesis;
pub mod word_pattern;

View File

@ -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::<Vec<_>>().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()
}

16
tests/word_pattern.rs Normal file
View File

@ -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
);
}