10. Regular Expression Matching

来源:互联网 发布:炫酷html5引导页源码 编辑:程序博客网 时间:2024/04/19 23:27


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


bool isMatch(char* s, char* p) {    //printf("%c %c %d %d\n",s[0],p[0],strlen(p),strlen(s));        //if(p[0]=='\0' && s[0]=='\0') //s,p为空不能用NULL标记    if(strlen(p)==0 && strlen(s)==0)    {        return true;    }        if(strlen(p)==1 && strlen(s)==1)    {        //printf("%d %d\n",s[0],p[0]);                //要么相等,要么p为.        if((s[0]==p[0]) || p[0]=='.')        {            return true;        }        else        {            return false;        }    }    //第二个字符不为*,s为空,返回false;    //否则比较第一个字符,从第二个字符开始进行递归匹配    if(p[1]!='*')    {        if(*s=='\0')        {            return false;        }        else        {            if(p[0]!='.' && p[0] != s[0])            {               // printf("Mark\n");                return false;            }            else            {                //printf("Mark\n");                return isMatch(s+1,p+1);            }        }    }    //接下来是*的情况    while (*s!='\0' && (p[0]==s[0] || p[0]=='.'))    {        if(isMatch(s,p+2))        {            return true;        }        else        {            s++;        }    }        //第一个字符和*前面的字符不相等的时候,就直接对p前两个字符的匹配过滤掉    return isMatch(s,p+2);}




0 0