-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrackets.cpp
More file actions
50 lines (36 loc) · 894 Bytes
/
brackets.cpp
File metadata and controls
50 lines (36 loc) · 894 Bytes
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
#include <stack>
#include <iostream>
bool is_match(char open, char close){
if(open == '(') return close == ')';
if(open == '{') return close == '}';
if(open == '[') return close == ']';
return false;
}
bool is_open(char ch){
if(ch == '(' || ch == '{' || ch == '[') return true;
return false;
}
int solution(std::string &S){
std::stack<char> stack;
for(char ch : S){
if(is_open(ch)) {
stack.push(ch);
}
else{
char from_stack = stack.top();
stack.pop();
if(!is_match(from_stack, ch)){
return 0;
}
}
}
if(!stack.empty()) return 0;
return 1;
}
int main(){
std::string str("{[()()]}");
std::string str1("([)()]");
std::cout << solution(str) << std::endl;
std::cout << solution(str1) << std::endl;
return 0;
}