LeetCode.010 Regular Expression Matching

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 // 字符     含义
 3 // .        匹配任意的单个字符
 4 // ^        匹配输入字符串的开头
 5 // $        匹配输入字符串的结尾
 6 // *        匹配前一个字符的零个或者多个出现
 7 #include <stdio.h>
 8 int matchhere(char *regexp, char *text);
 9 
10 int matchstar(int c, char *regexp, char *text) {// matchstar: search for c*regexp at beginning of text
11    do {// a * matches zero or more instances
12        if (matchhere(regexp, text)) return 1;
13    } while (*text != '\0' && (*text++ == c || c == '.'));
14    return 0;
15 }
16 int matchhere(char *regexp, char *text) {// matchhere: search for regexp at beginning of text
17    if (regexp[0] == '\0') return 1;
18    if (regexp[1] == '*') return matchstar(regexp[0], regexp+2, text);
19    if (regexp[0] == '$' && regexp[1] == '\0') return *text == '\0';
20    if (*text!='\0' && (regexp[0]=='.' || regexp[0]==*text)) return matchhere(regexp+1, text+1);
21    return 0;
22 }
23 
24 int match(char *regexp, char *text) {// match: search for regexp anywhere in text
25     if (regexp[0] == '^') return matchhere(regexp+1, text);
26     do {// must look even if string is empty
27         if (matchhere(regexp, text)) return 1;
28     } while (*text++ != '\0');
29     return 0;
30 }
View Code

下面是自己的关于此题的代码。

 1 bool isMatch(char* s, char* p);
 2 bool matchstar(int c,char *s,char *p)  
 3 {
 4     do {// a * matches zero or more instances
 5         if (isMatch(s, p)) return 1;
 6     } while (*s != '\0' && (*s++ == c || c == '.'));
 7     return 0;
 8 }
 9 bool isMatch(char* s, char* p) {
10     if(p[0]=='\0' && s[0]=='\0') return 1;
11     if(p[1]=='*') return matchstar(p[0], s,p+2);
12     if(*s!='\0' && (p[0]=='.' || *s==p[0])) return isMatch(s+1,p+1);
13     return 0;
14     
15 }

 

posted @ 2015-07-19 13:37  Mad.King  阅读(162)  评论(0)    收藏  举报