-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy path10.正则表达式匹配.cpp
73 lines (67 loc) · 1.55 KB
/
10.正则表达式匹配.cpp
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
/*
* @lc app=leetcode.cn id=10 lang=cpp
*
* [10] 正则表达式匹配
*/
// @lc code=start
class Solution
{
public:
std::unordered_map<std::string, bool> visited;
bool dp(const std::string &s, int sp,
const std::string &p, int pp)
{
if (pp == p.size())
{
return sp == s.size();
}
if (sp == s.size())
{
if ((p.size() - pp) % 2 == 1)
{
return false;
}
for (; pp + 1 < p.size(); pp += 2)
{
if (p[pp + 1] != '*')
{
return false;
}
}
return true;
}
std::string key = std::to_string(sp) + "," + std::to_string(pp);
if (visited.count(key) != 0)
{
return visited[key];
}
if (s[sp] == p[pp] || p[pp] == '.')
{
if (pp < p.size() - 1 && p[pp + 1] == '*')
{
visited[key] = (dp(s, sp, p, pp + 2) || dp(s, sp + 1, p, pp));
}
else
{
visited[key] = dp(s, sp + 1, p, pp + 1);
}
}
else
{
if (pp < p.size() - 1 && p[pp + 1] == '*')
{
visited[key] = dp(s, sp, p, pp + 2);
}
else
{
visited[key] = false;
}
}
return visited[key];
}
bool isMatch(string s, string p)
{
return dp(s, 0, p, 0);
}
};
// @lc code=end