-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
49 lines (45 loc) · 1.39 KB
/
Copy pathsolution.cpp
File metadata and controls
49 lines (45 loc) · 1.39 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
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool wildCard(string &txt, string &pat)
{
int n = txt.size();
int m = pat.size();
// prev[j] -> dp for previous i (i-1)
vector<bool> prev(m + 1, false), cur(m + 1, false);
prev[0] = true; // empty text matches empty pattern
// empty text vs pattern: only true when pattern prefix is all '*'
for (int j = 1; j <= m; ++j)
{
if (pat[j - 1] == '*')
prev[j] = prev[j - 1];
else
prev[j] = false;
}
for (int i = 1; i <= n; ++i)
{
cur[0] = false; // non-empty text cannot match empty pattern
for (int j = 1; j <= m; ++j)
{
if (pat[j - 1] == '*')
{
// '*' matches empty (cur[j-1]) or matches one more char (prev[j])
cur[j] = cur[j - 1] || prev[j];
}
else if (pat[j - 1] == '?' || pat[j - 1] == txt[i - 1])
{
cur[j] = prev[j - 1];
}
else
{
cur[j] = false;
}
}
// move cur to prev for next iteration
prev.swap(cur);
}
return prev[m];
}
};