diff options
author | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
---|---|---|
committer | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
commit | d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch) | |
tree | 96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /word_pattern.rs | |
download | leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip |
initial
Diffstat (limited to 'word_pattern.rs')
-rw-r--r-- | word_pattern.rs | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/word_pattern.rs b/word_pattern.rs new file mode 100644 index 0000000..6161b40 --- /dev/null +++ b/word_pattern.rs @@ -0,0 +1,26 @@ +struct Solution; + +impl Solution { + pub fn word_pattern(pattern: String, s: String) -> bool { + use std::collections::{HashMap, HashSet}; + if pattern.len() != s.matches(' ').count() + 1 { + return false; + } + let (mut hm, mut word_set) = (HashMap::new(), HashSet::new()); + for (word, c) in s.split_ascii_whitespace().zip(pattern.chars()) { + if let Some(w) = hm.insert(c, word) { + if w != word { + return false; + } + } else if !word_set.insert(word) { + return false; + } + } + true + } +} + +fn main() { + let (pattern, s) = (String::from("abba"), String::from("dog cat cat dog")); + print!("{}", Solution::word_pattern(pattern, s)); +} |