-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwildcard_matching.cpp
More file actions
86 lines (80 loc) · 2.24 KB
/
wildcard_matching.cpp
File metadata and controls
86 lines (80 loc) · 2.24 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <string>
#include <vector>
#include <iostream>
using namespace std;
/**
* Descirbe: Implement wildcard pattern matching with support for '?' and '*'.
*
* Using dynamic programming get an O(len(s) * len(p)) algorithm
*/
class Solution {
public:
/**
* @param s: A string
* @param p: A string includes "?" and "*"
* @return: A boolean
*/
bool isMatch(const char *s, const char *p) {
// About the empty string.
if (!s && !p) {
return true;
}
if (!p) {
return false;
}
const char *s_cur = s;
const char *p_cur = p;
int s_len = 0;
int p_len = 0;
// Get the length of the two string.
while (*s_cur != '\0') {
++s_len;
++s_cur;
}
while (*p_cur != '\0') {
++p_len;
++p_cur;
}
// Record the preceding information.
vector<vector<bool>> dp(p_len + 1, vector<bool>(s_len + 1, false));
dp[0][0] = true;
for (int i = 1; i <= p_len; ++i) {
if (*(p + i - 1) == '*') {
for (int j = 0; j <= s_len; ++j) {
// The following is matched obviously.
if (dp[i - 1][j]) {
for (int k = j; k <= s_len; ++k) {
dp[i][k] = true;
}
break;
}
}
} else if (*(p + i - 1) == '?') {
for (int j = 0; j < s_len; ++j) {
// Based on the previous one.
if (dp[i - 1][j]) {
dp[i][j + 1] = true;
}
}
} else {
for (int j = 1; j <= s_len; ++j) {
// Based on the previous one.
if (dp[i - 1][j - 1] && *(p + i - 1) == *(s + j - 1)) {
dp[i][j] = true;
}
}
}
}
return dp[p_len][s_len];
}
};
int main() {
Solution so;
string p, s;
while (cin >> s) {
cin >> p;
auto re = so.isMatch(s.c_str(), p.c_str());
cout << "result: " << re << endl;
}
return 0;
}