10. Regular Expression Matching

来源:互联网 发布:中文域名购买 编辑:程序博客网 时间:2024/04/26 07:26

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,所以用C来实现。这里用递归的方法实现。要注意的地方是‘*‘符号,因为x*可以代表0到任意个x,所以每次遇到'*'号,就分两个分支,一个是p跳过x*(即看做是0个x),另一个是匹配一个x且p保持在x*的位置进行递归。用C的话,直接用指针遍历字符串,很方便。


代码:

bool isMatch(char* s, char* p) {    if(*p == 0) return *s == 0;    printf("s: %s\tp: %s\n", s, p);    if(p[1] == '*')    {    return isMatch(s, p + 2) || ((*s != 0 && (s[0] == p[0] || p[0] == '.')) && isMatch(s + 1, p));}else{return ((*s != 0 && (s[0] == p[0] || p[0] == '.')) && isMatch(s + 1, p + 1));}}


0 0
原创粉丝点击