Skip to content

Commit 33d1aec

Browse files
committed
isMatch.cpp
1 parent 6ad59a8 commit 33d1aec

1 file changed

Lines changed: 68 additions & 0 deletions

File tree

‎LeetCode/isMatch.cpp‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
#include <iostream>
2+
#include <vector>
3+
using namespace std;
4+
5+
vector<vector<int> > mm;
6+
string strs, strp;
7+
int lens, lenp;
8+
9+
int isok(int idxs, int idxp) {
10+
int& ret = mm[idxs][idxp];
11+
if (ret != -1) return ret;
12+
ret = 0;
13+
if (idxp == lenp) {
14+
if (idxs == lens) return ret = 1;
15+
else return ret;
16+
}
17+
if (strp[idxp] == '.') {
18+
if (idxp + 1 < lenp && strp[idxp + 1] == '*') {
19+
for (int i = idxs; i <= lens; ++i) {
20+
if (isok(i, idxp + 2)) {
21+
return ret = 1;
22+
}
23+
}
24+
} else if (idxs < lens && isok(idxs + 1, idxp + 1)) {
25+
return ret = 1;
26+
}
27+
} else {
28+
if (idxp + 1 < lenp && strp[idxp + 1] == '*') {
29+
if (isok(idxs, idxp + 2)) {
30+
return ret = 1;
31+
}
32+
for (int i = idxs; i < lens; ++i) {
33+
if (strs[i] != strp[idxp]) break;
34+
if (isok(i + 1, idxp + 2)) {
35+
return ret = 1;
36+
}
37+
}
38+
} else if (idxs < lens && strs[idxs] == strp[idxp] && isok(idxs + 1, idxp + 1)) {
39+
return ret = 1;
40+
}
41+
}
42+
return ret;
43+
}
44+
45+
class Solution {
46+
public:
47+
bool isMatch(const char *s, const char *p) {
48+
strs = string(s);
49+
strp = string(p);
50+
lens = strs.length();
51+
lenp = strp.length();
52+
mm.clear();
53+
mm.resize(lens + 5, vector<int>(lenp + 5, -1));
54+
return isok(0, 0) == 1;
55+
}
56+
};
57+
58+
int main() {
59+
Solution s = Solution();
60+
cout << s.isMatch("aa", "a") << endl;
61+
cout << s.isMatch("aa", "aa") << endl;
62+
cout << s.isMatch("aaa", "aa") << endl;
63+
cout << s.isMatch("aa", "a*") << endl;
64+
cout << s.isMatch("aa", ".*") << endl;
65+
cout << s.isMatch("ab", ".*") << endl;
66+
cout << s.isMatch("aab", "c*a*b") << endl;
67+
return 0;
68+
}

0 commit comments

Comments
 (0)