-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths0290_word_pattern.rs
More file actions
61 lines (55 loc) · 1.56 KB
/
s0290_word_pattern.rs
File metadata and controls
61 lines (55 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#![allow(unused)]
pub struct Solution {}
use std::collections::HashMap;
impl Solution {
// O(n) O(n)
pub fn word_pattern(pattern: String, s: String) -> bool {
let mut word_map = HashMap::new();
let mut char_map = HashMap::new();
let words = s.split(' ').collect::<Vec<&str>>();
let chs = pattern.chars().collect::<Vec<char>>();
if words.len() != chs.len() {
return false;
}
for i in 0..words.len() {
let ch = chs[i];
let w = words[i];
if !char_map.contains_key(&ch) {
if word_map.contains_key(&w) {
return false;
} else {
char_map.insert(ch, w);
word_map.insert(w, ch);
}
} else {
if *char_map.get(&ch).unwrap() != w {
return false;
}
}
}
true
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_290() {
assert_eq!(
Solution::word_pattern("abba".to_string(), "dog cat cat dog".to_string(),),
true
);
assert_eq!(
Solution::word_pattern("abba".to_string(), "dog cat cat fish".to_string(),),
false
);
assert_eq!(
Solution::word_pattern("aaaa".to_string(), "dog cat cat dog".to_string(),),
false
);
assert_eq!(
Solution::word_pattern("abba".to_string(), "dog dog dog dog".to_string(),),
false
);
}
}