-
Notifications
You must be signed in to change notification settings - Fork 0
/
20. Valid Parentheses
62 lines (51 loc) · 1.08 KB
/
20. Valid Parentheses
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
const int ZERO = [](){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
return 0;
}();
class Solution {
public:
bool isValid(string s)
{
size_t size = s.size();
if(size & 1)
{
return false;
}
list<char> p(1, s.front());
for(size_t i = 1; i < size; ++i)
{
if(p.back() + 2 == s[i] || p.back() + 1 == s[i])
{
p.pop_back();
}
else
{
p.push_back(s[i]);
}
}
return p.empty();
}
bool isValidStack(string_view s)
{
size_t size = s.size();
if(size & 1)
{
return false;
}
stack<char, vector<char>> p;
p.push(s.front());
for(size_t i = 1; i < size; ++i)
{
if(p.top() + 2 == s[i] || p.top() + 1 == s[i])
{
p.pop();
}
else
{
p.push(s[i]);
}
}
return p.empty();
}
};