forked from sunstick/code-street
-
Notifications
You must be signed in to change notification settings - Fork 0
/
regular_expression_matching.cpp
41 lines (34 loc) · 1.02 KB
/
regular_expression_matching.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
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
*/
class Solution {
public:
bool isMatch(const char *s, const char *p) {
if (*p == 0) return *s == 0;
if (*(p + 1) == '*') {
while ((*p == *s) || (*p == '.' && *s != 0))
if (isMatch(s, p + 2))
return true;
else s++;
return isMatch(s, p + 2);
} else {
if ((*p == *s) || (*p == '.' && *s != 0))
return isMatch(s + 1, p + 1);
else
return false;
}
}
};