regular expression matching leetcode

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

思路分析:本题先采用暴力穷举方法。然而发现题目还是存在不少缺陷的。

思路也是参考了网上的诸多题解,现总结如下:
  • 注意,我们只是判断当前这一次是否能够匹配,并且基于s和p之前的元素已经匹配,代码当中我已经列出一种反例。s="ab",p="cdab" false s="a" p="ab" false
  • s和p都是指针,s指向s[0],p指向p[0]。
  • 如果p[1]!='*'并且p[0]!='.' 此时若s[0]!=p[0],则函数结束,返回false,否则s、p后移指向下一个元素并继续递归判断。
  • 如果p[1]=='*'那么此时看从s开始的子串,假设s[0],s[1],...s[k]都等于p[0]那么意味着这些都有可能是合适的匹配,那么递归对于剩下的(s,p+2),(s+1,p+2),...,(s+k,p+2)都要尝试(p+2是因为跳过当前和下一个'*'字符)。

    

  if (!p[0])
  return !s[0];//这个也是最后递归结束的点,非常重要,因为当s指向''的时候,仔细一分析竟然还有好多缺陷,不过这一句确实是个递归结束点。

 1 #include<stdio.h>
 2 #include<string>
 3 
 4 bool isMatch(char* s, char* p) {
 5     if (!p[0])
 6         return !s[0];
 7 
 8     int slen = strlen(s), plen = strlen(p);
 9     if (plen == 1 || p[1] != '*')
10         return slen && (p[0] == '.' || s[0] == p[0])
11         && isMatch(s + 1, p + 1);
12     while (s[0] && (p[0] == '.' || s[0] == p[0]))
13     if (isMatch(s++, p + 2))
14         return true;
15     return isMatch(s, p + 2);
16 }
17 
18 int main()
19 {
20     char *s = "ab";
21     char *p = "cdab";
22     bool res = isMatch(s, p);
23     printf("%d
", res);//结果为0
24     return 0;
25 }
View Code



手里拿着一把锤子,看什么都像钉子,编程界的锤子应该就是算法了吧!
原文地址:https://www.cnblogs.com/chess/p/4707590.html