标签:
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
思路分析:本题先采用暴力穷举方法。然而发现题目还是存在不少缺陷的。
思路也是参考了网上的诸多题解,现总结如下:
if (!p[0])
return !s[0];//这个也是最后递归结束的点,非常重要,因为当s指向‘\0‘的时候,仔细一分析竟然还有好多缺陷,不过这一句确实是个递归结束点。。
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\n", res);//结果为0 24 return 0; 25 }
regular expression matching leetcode
标签:
原文地址:http://www.cnblogs.com/chess/p/4707590.html