-
Notifications
You must be signed in to change notification settings - Fork 0
/
ParenthesesBalance.cpp
72 lines (67 loc) · 1.51 KB
/
ParenthesesBalance.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
/** https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=614
* #stack
*/
#include<iostream>
#include<string>
#include<deque>
using namespace std;
char validPairChar(char c) {
if (c == ']') {
return '[';
} else if (c == ')') {
return '(';
} else {
return c;
}
}
string check(string& str) {
deque<char> stack;
for (string::iterator it = str.begin(); it != str.end(); it++) {
char c = *it;
#ifdef _BETTER
if (stack.empty()) {
stack.push_front(c);
} else {
if (c != validPairChar(c)) {
if (stack.front() != validPairChar(c)) {
return "No";
} else {
stack.pop_front();
}
} else {
stack.push_front(c);
}
}
#else _BETTER
// general way
if (c == '(' || c == '[')
stack.push_front(c);
else { // close
if (stack.empty() || validPairChar(c) != stack.front()) {
return "No";
} else {
stack.pop_front();
}
}
#endif // _BETTER
}
if (!stack.empty()) {
return "No";
}
return "Yes";
}
int main() {
string str;
int n;
cin >> n;
getline(cin, str);
string arr[n];
for (int i=0; i < n; i++) {
getline(cin, str);
arr[i] = str;
}
for(string& str : arr) {
cout << check(str) << endl;
}
return 0;
}