[leetcode 10] Regular Expression Matching

来源:互联网 发布:伊戈尔·克鲁托伊 知乎 编辑:程序博客网 时间:2024/05/09 02:10

题目:

'.' 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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "a*") → trueisMatch("aa", ".*") → trueisMatch("ab", ".*") → trueisMatch("aab", "c*a*b") → true

思路:

1.题目要求实现一个正则表达式;
2.为s串和p串各设立一个指针,从头开始遍历;
3.分析题目,由于'.'和'*'只在p中出现,而且p中的‘x‘可以匹配s中的0个或n个x,所以可以将整个遍历过程分为两种情况,即*(p+1)!='*'和*(p+1)=='*';
4.对于*(p+1)!='*'的情况,如果s和p的当前指针所指字符不相等或者s已经遍历到末尾,那么即可直接返回false,否则两个指针各走一步,进行下一步比较;
5.对于*(p+1)=='*'的情况,如果s当前字符与p所指当前字符不等,那么就意味着p中*匹配s中0个当前字符,所以可以直接比较*(s)和*(p+2),如果s当前字符与p所指当前字符相等,则比较*(s)与*(p+2),因为无法确定p中的*匹配s中多少个当前字符,如果上述比较成立,那么直接返回结果(此比较基于递归),若上述比较不成立,则在s所指字符与p所指字符相等的前提下,一直向前移动s,然后返回比较s与p+2所指字符比较的结果;
6.因为p中的*可以匹配s中0个或n个字符,所以p的长度必然小于s的长度,所以遍历结束条件为p遍历结束,若p结束但s未结束,则可直接返回false。

代码:

class Solution{public:bool isMatch(const char *s,const char *p){if(*p=='\0')return (*s=='\0');if(*(p+1)!='*'){if(*s!=*p && *p!='.' || *s=='\0')return false;else return isMatch(s+1,p+1);}else if(*(p+1)=='*'){while(*s!='\0' && (*s==*p || *p=='.')){if(isMatch(s,p+2))return true;++s;}return isMatch(s,p+2);}}};


0 0
原创粉丝点击