-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathregular_expression_matching.rs
More file actions
87 lines (75 loc) · 2.62 KB
/
regular_expression_matching.rs
File metadata and controls
87 lines (75 loc) · 2.62 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
use std::collections::HashMap;
pub struct Solution;
impl Solution {
pub fn is_match(text: String, pattern: String) -> bool {
fn dfs(
i: usize,
j: usize,
t: &[u8],
p: &[u8],
cache: &mut HashMap<(usize, usize), bool>,
) -> bool {
if let Some(&v) = cache.get(&(i, j)) {
return v;
}
if p.is_empty() {
return t.is_empty();
}
if i >= t.len() && j >= p.len() {
return true;
}
if j >= p.len() {
return false;
}
let first_match = i < t.len() && (p[j] == b'.' || p[j] == t[i]);
if (j + 1) < p.len() && p[j + 1] == b'*' {
let result =
(dfs(i, j + 2, t, p, cache)) || (first_match && dfs(i + 1, j, t, p, cache));
let _ = &cache.insert((i, j), result);
result
} else {
let result = first_match && dfs(i + 1, j + 1, t, p, cache);
let _ = &cache.insert((i, j), result);
result
}
}
let mut cache: HashMap<(usize, usize), bool> = HashMap::new();
return dfs(0, 0, text.as_bytes(), pattern.as_bytes(), &mut cache);
}
pub fn is_match_brute(text: String, pattern: String) -> bool {
if pattern.is_empty() {
return text.is_empty();
}
let first_match = !text.is_empty()
&& (pattern.as_bytes()[0] == text.as_bytes()[0]
|| pattern.as_bytes()[0] as char == '.');
if pattern.len() >= 2 && pattern.as_bytes()[1] as char == '*' {
return (Self::is_match(
text.clone(),
match pattern.get(2..) {
None => String::from(""),
Some(n) => String::from(n),
},
)) || (first_match
&& Self::is_match(
match text.get(1..) {
None => String::from(""),
Some(n) => String::from(n),
},
pattern,
));
} else {
return first_match
&& Self::is_match(
match text.get(1..) {
None => String::from(""),
Some(n) => String::from(n),
},
match pattern.get(1..) {
None => String::from(""),
Some(n) => String::from(n),
},
);
}
}
}