-
Notifications
You must be signed in to change notification settings - Fork 1
/
290.word-pattern.rs
41 lines (35 loc) · 1.01 KB
/
290.word-pattern.rs
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
/*
* @lc app=leetcode id=290 lang=rust
*
* [290] Word Pattern
*/
// @lc code=start
use std::collections::HashMap;
impl Solution {
pub fn word_pattern(pattern: String, str: String) -> bool {
let mut forward = HashMap::new();
let mut backward = HashMap::new();
let words: Vec<&str> = str.split(' ').collect();
if pattern.len() != words.len() {
return false;
}
for (i, ch) in pattern.chars().enumerate() {
if forward.contains_key(&ch) {
if forward.get(&ch).unwrap() != words[i] {
return false;
}
} else {
forward.insert(ch, words[i].to_owned());
}
if backward.contains_key(words[i]) {
if backward.get(words[i]).unwrap() != &ch {
return false;
}
} else {
backward.insert(words[i].to_owned(), ch);
}
}
return true;
}
}
// @lc code=end