Skip to content

Commit 913502a

Browse files
committed
Add 'Regular Expression Matching' solution.
1 parent d3498d9 commit 913502a

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

Find_Minimum_in_Rotated_Sorted_Array_II.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,4 +32,4 @@ class Solution {
3232
int findMin(vector<int> &num) {
3333
return findSubMin(num, 0, num.size()-1);
3434
}
35-
};
35+
};

Regular_Expression_Matching.cpp

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*
2+
'.' Matches any single character.
3+
'*' Matches zero or more of the preceding element.
4+
5+
The matching should cover the entire input string (not partial).
6+
7+
The function prototype should be:
8+
bool isMatch(const char *s, const char *p)
9+
10+
Some examples:
11+
isMatch("aa","a") ¡ú false
12+
isMatch("aa","aa") ¡ú true
13+
isMatch("aaa","aa") ¡ú false
14+
isMatch("aa", "a*") ¡ú true
15+
isMatch("aa", ".*") ¡ú true
16+
isMatch("ab", ".*") ¡ú true
17+
isMatch("aab", "c*a*b") ¡ú true
18+
*/
19+
20+
class Solution {
21+
public:
22+
bool isEqual(char s, char p) {
23+
if (s == p || p == '.' && s != '\0') return true;
24+
return false;
25+
}
26+
27+
bool isMatch(const char *s, const char *p) {
28+
if (*s == '\0' && *p == '\0') return true;
29+
30+
if (*p != '\0' && *(p + 1) == '*') {
31+
// '*' represents zero of preceding element.
32+
if (isMatch(s, p + 2)) return true;
33+
// '*' represents one or more of preceding element.
34+
while (isEqual(*s, *p)) {
35+
++s;
36+
if (isMatch(s, p + 2)) return true;
37+
}
38+
} else if (isEqual(*s, *p)) {
39+
if (isMatch(s + 1, p + 1)) return true;
40+
}
41+
42+
return false;
43+
}
44+
};

0 commit comments

Comments
 (0)