Implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true

 1         public static bool RegularExpressionMatching(string s, string p)
 2         {
 3             //if s.Length == 0 check if p has * after each character
 4             if (s.Length == 0)
 5                 return RegularExpressionMatching_CheckEmpty(p);
 6             //if s.Length >= 0 and p.Length == 0, return false
 7             if (p.Length == 0)
 8                 return false;
 9 
10             char s1 = s[0];
11             char p1 = p[0];
12             char p2 = p.Length > 1 ? p[1] : '0'; //any character but '*' will work
13 
14             if (p2 == '*')
15             {
16                 if (p1 == '.' || s1 == p1)
17                 {
18                     return RegularExpressionMatching(s.Substring(1), p) || RegularExpressionMatching(s, p.Substring(2));
19                 }
20                 else
21                 {
22                     return RegularExpressionMatching(s, p.Substring(2));
23                 }
24             }
25             else
26             {
27                 if (p1 == '.' || s1 == p1)
28                 {
29                     return RegularExpressionMatching(s.Substring(1), p.Substring(1));
30                 }
31                 else
32                     return false;
33             }
34         }
35 
36         public static bool RegularExpressionMatching_CheckEmpty(string p)
37         {
38             if (p.Length % 2 != 0)
39                 return false;
40 
41             for (int i = 1; i < p.Length; i += 2)
42             {
43                 if (p[i] != '*')
44                     return false;
45             }
46 
47             return true;
48         }

代码分析:

  递归。

  1. 当s.Length == 0 的时候,看p是不是每个字符后面都有 '*',像 "a*.*j*u*",不然就返回false

  2. 如果p递归到最后一个了,就只看if (p1 == '.' || p1 = s1), 所以 p2 随便给个 '0' 只要不是'*'都可以。

  3. 1) 如果p2 == '*' 而且 p1 == '.' || s1 == p1, 那么就 递归进去 返回 p1 字符当 1 个用 或者 p1 字符当 0 个用 的结果。

    2) 如果p2 != '*' 而且 p1 == '.' || s1 == p1, 那么递归进去 返回 p1之后的 与 s1之后的字符串 比较结果。 否者 返回 false

  DP应该也是可以的,但是好像比较复杂。

相关文章:

  • 2022-12-23
  • 2021-12-28
  • 2021-05-22
  • 2021-06-04
  • 2022-02-16
  • 2021-05-22
  • 2021-09-08
猜你喜欢
  • 2021-10-14
  • 2021-06-07
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案