rustgym/leetcode/
_10_regular_expression_matching.rs1struct Solution;
2
3impl Solution {
4 fn is_match(s: String, p: String) -> bool {
5 let n = s.len();
6 let m = p.len();
7 let s: Vec<char> = s.chars().collect();
8 let p: Vec<char> = p.chars().collect();
9 let mut memo: Vec<Vec<Option<bool>>> = vec![vec![None; m + 1]; n + 1];
10 Self::is_match_dp(n, m, &mut memo, &s, &p)
11 }
12
13 fn is_match_dp(
14 n: usize,
15 m: usize,
16 memo: &mut Vec<Vec<Option<bool>>>,
17 s: &[char],
18 p: &[char],
19 ) -> bool {
20 if let Some(ans) = memo[n][m] {
21 ans
22 } else {
23 let res = if n == 0 && m == 0 {
24 true
25 } else if n != 0 && m == 0 {
26 false
27 } else if n == 0 && m != 0 {
28 if p[m - 1] == '*' {
29 Self::is_match_dp(n, m - 2, memo, s, p)
30 } else {
31 false
32 }
33 } else {
34 if s[n - 1] == p[m - 1] {
35 Self::is_match_dp(n - 1, m - 1, memo, s, p)
36 } else {
37 match p[m - 1] {
38 '*' => match p[m - 2] {
39 '*' => false,
40 '.' => {
41 Self::is_match_dp(n - 1, m, memo, s, p)
42 || Self::is_match_dp(n, m - 2, memo, s, p)
43 }
44 _ => {
45 if s[n - 1] != p[m - 2] {
46 Self::is_match_dp(n, m - 2, memo, s, p)
47 } else {
48 Self::is_match_dp(n - 1, m, memo, s, p)
49 || Self::is_match_dp(n, m - 2, memo, s, p)
50 }
51 }
52 },
53 '.' => Self::is_match_dp(n - 1, m - 1, memo, s, p),
54 _ => false,
55 }
56 }
57 };
58
59 memo[n][m] = Some(res);
60 res
61 }
62 }
63}
64
65#[test]
66fn test() {
67 let s = "aa".to_string();
68 let p = "a".to_string();
69 let res = false;
70 assert_eq!(Solution::is_match(s, p), res);
71 let s = "aa".to_string();
72 let p = "a*".to_string();
73 let res = true;
74 assert_eq!(Solution::is_match(s, p), res);
75 let s = "ab".to_string();
76 let p = ".*".to_string();
77 let res = true;
78 assert_eq!(Solution::is_match(s, p), res);
79 let s = "aab".to_string();
80 let p = "c*a*b".to_string();
81 let res = true;
82 assert_eq!(Solution::is_match(s, p), res);
83 let s = "mississippi".to_string();
84 let p = "mis*is*p*.".to_string();
85 let res = false;
86 assert_eq!(Solution::is_match(s, p), res);
87}