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)感觉要考虑的东西很多啊,测试了很多次才通过的。
(2)测试案例:
s=”“;p=".*"
s="";p="c*c*"。
s="aaa";p="ab*c*a"
(3)其中很重要的地方是用到了递归
例如p = a*abc;s = aaabc;我们递归成为
isMatch("aaabc","abc"),isMatch("aabc","abc"),isMatch("abc","abc"),isMatch("bc","abc"), 也就是掉0个a,1个a,2个a,3个a的情况,主要看看s里面开头有多少个a的例如p=.*abc;s=abc;我们就递归为
isMatch("abc","abc"),isMatch("bc","abc"),isMatch("c","abc"),isMatch("","abc"),只要有一个是ture就为真。
(4)当p=”abc“ s=”c*bc“
因为a!=c;因此我们直接将指针向右移2。
(5)因为是通过s来检测p
考虑当s不是空,但是p是空的时候:即s=”abc“;p="abcc*"或者s=”abc“;p="abc*"
#include <iostream> using namespace std; bool isMatch(const char *s, const char *p) { const char *A = s; const char *B = p; if(B == NULL) { if(A!=NULL) return false; } if(*B == '\0') { if(*A!='\0') return false; } while(*B!='\0') { if(*B=='.' && *A!='\0') { if(*A == '\0') return false; else{ B++; A++; continue; } } if(*B == *A) { B++; A++; continue; } if(*B != *A ) { if(*(B+1) == '*') { B = B + 2; continue; } } if(*B == '*') { if(B==p) { B++; continue; } char c = *(B-1); B++; if(c == '.' && *B == '\0') return true; if(c == '.' && *B!='\0') { bool flag = false; A--; while(*A!='\0') { bool res = isMatch(A, B); if(res == true) flag = true; A++; } bool res = isMatch(A, B); if(res == true) flag = true; return flag; } bool flag = false; A--; while(*A == c ) { bool res = isMatch(A, B); if(res == true) flag = true; A++; } bool res = isMatch(A, B); if(res == true) flag = true; return flag; } if(*A == '\0') { if(*(B) == '*' && *(B+1) == *(A-1) && *(B+2) == '\0') return true; else if(*(B+1) == '*' && *(B+2) == '\0') return true; else return false; } <strong><span style="color:#FF0000;">return false;</span><span style="color:#FF6666;">//当前面条件不满足的时候即使不匹配的,应该要加上的,不然会死循环</span></strong> } if(*A == '\0') return true; else return false; } int main(void) { // const char *s = "aaa"; // const char *p = "ab*a*c*a"; const char *s = ""; const char *p = "c*c*"; cout << "s:" << s << " p:" << p << endl; bool res = isMatch(s, p); cout << res << endl; system("pause"); return 0; }