-
Notifications
You must be signed in to change notification settings - Fork 0
/
#20 ValidParentheses.cpp
43 lines (39 loc) · 1.11 KB
/
#20 ValidParentheses.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
#include <map>
#include "Header.h"
//"Valid Parentheses"
//https://leetcode.com/problems/valid-parentheses
class Solution {
public:
bool isValid(string s) {
if (s.size() < 2) {
return false;
}
else {
map<char, char>DATA;
DATA['('] = ')';
DATA['{'] = '}';
DATA['['] = ']';
map<char, bool>BACK_OR_NO;
BACK_OR_NO['('] = 1;
BACK_OR_NO['{'] = 1;
BACK_OR_NO['['] = 1;
BACK_OR_NO['}'] = 0;
BACK_OR_NO[')'] = 0;
BACK_OR_NO[']'] = 0;
vector<char>to_close;
for (auto it = begin(s); it != end(s); it++) {
if (BACK_OR_NO[*it] == 0 &&
(to_close.size() == 0 || DATA[to_close.back()] != *it)) {
return false;
}
else if (BACK_OR_NO[*it]==1) {
to_close.push_back(*it);
}
else {
to_close.pop_back();
}
}
return to_close.empty();
}
}
};