forked from rost0413/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRegular_Expression_Matching.cpp
More file actions
59 lines (53 loc) · 1.35 KB
/
Regular_Expression_Matching.cpp
File metadata and controls
59 lines (53 loc) · 1.35 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
Author: Weixian Zhou, ideazwx@gmail.com
Date: Jul 11, 2012
Problem: Regular Expression Matching
Difficulty: hard
Source: http://www.leetcode.com/onlinejudge
Notes:
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
Solution:
The basic idea is recursion. The boundry condition is not easy.
*/
#include <vector>
#include <set>
#include <climits>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <cmath>
#include <cstring>
using namespace std;
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;
}
s++;
}
return isMatch(s, p + 2);
} else if ((*p == '.' && *s != '\0') || *s == *p) {
return isMatch(s + 1, p + 1);
}
return false;
}
};