23 lines
713 B
Rust
23 lines
713 B
Rust
|
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()
|
||
|
}
|