-
Notifications
You must be signed in to change notification settings - Fork 7
/
parenthesis_checker.cpp
52 lines (49 loc) · 964 Bytes
/
parenthesis_checker.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
#include <iostream>
#include <algorithm>
#include <climits>
#include <stack>
using namespace std;
class Solution {
public:
bool isMatching(char c1, char c2) {
if (c1 == '(' && c2 == ')') {
return true;
} else if (c1 == '{' && c2 == '}') {
return true;
} else if (c1 == '[' && c2 == ']') {
return true;
}
else {
return false;
}
}
bool isValid(string s) {
stack <char> st;
for (int i = 0; i < s.size(); ++i) {
if (s[i] == '(' || s[i] == '{' || s[i] == '[') {
st.push(s[i]);
}
if (s[i] == ')' || s[i] == '}' || s[i] == ']') {
if (st.empty()) {
return false;
}
else if (!isMatching(st.top(), s[i])) {
return false;
}
st.pop();
}
}
if (st.empty()) {
return true;
} else {
return false;
}
}
};
int main() {
string str;
cin >> str;
Solution s;
s.isValid(str) ? cout << "true\n" : cout << "false\n";
return 0;
}