Regular Expression Matching

来源:互联网 发布:国家网络空间安全战略 编辑:程序博客网 时间:2024/06/05 22:40

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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "a*") → trueisMatch("aa", ".*") → trueisMatch("ab", ".*") → trueisMatch("aab", "c*a*b") → true
c*是一体的,0个或多个!!!
 此题为正则表达式部分的实现。

借鉴:http://leetcode.com/2011/09/regular-expression-matching.html

利用有限自动机的思路。前部分实现字符以及"."的匹配,后面为*的,并存在一定关系。

 bool isMatch(const char *s, const char *p) {                if( *p == '\0')return *s == '\0';                // 下一字符非*---》针对正则表达式        if(*(p+1) != '*')        {            return (*p == *s || (*p == '.'&& *s != '\0')) && isMatch(s+1,p+1);        }                while(*p == *s || (*p == '.'&& *s != '\0'))//处理带*的分支        {            if(isMatch(s,p+2))return true; //处理形如0个或多个重复!"aaa", "a*a"            s++;        }        return isMatch(s,p+2);//s本来就已经自增了,不必做处理    }


以下为个人理解:


0 0
原创粉丝点击