-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathbracket_balance.cpp
More file actions
88 lines (78 loc) · 1.71 KB
/
bracket_balance.cpp
File metadata and controls
88 lines (78 loc) · 1.71 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <cstdio>
#include <iostream>
using namespace std;
template <class T>
class Stack{
private:
int _size;
int _head;
T* _data;
public:
Stack(int size){
_size = size;
_head = -1;
_data = new T[size];
}
void push(T data){
if (_head == _size - 1)
{
cout << "Stack full" << endl;
return;
}
_data[++_head] = data;
}
T& head(){
if (_head == -1)
throw exception();
return _data[_head];
}
T& pop(){
if (_head == -1)
throw exception();
_head--;
return _data[_head];
}
bool empty(){
return _head == -1;
}
void print(){
for (int i = 0; i <= _head; i++){
cout << &_data[i] << " ";
}
cout << endl;
}
};
int main(){
string str = "";
Stack<char> s(10);
bool unbalanced = false;
for (int i=0; i < str.length(); i++){
char c = str[i];
if (c == '(' || c == '{' || c == '['){
s.push(c);
}
else if (c == ')' || c == '}' || c == ']'){
if (s.empty()){
cout << "unbalanced" << endl;
unbalanced = true;
break;
}
char h = s.head();
if (
(c == ')' && h == '(') ||
(c == '}' && h == '{') ||
(c == ']' && h == '[')
){
s.pop();
}
else{
cout << "unbalanced" << endl;
break;
}
}
}
if (!unbalanced && s.empty()){
cout << "balanced" << endl;
}
return 0;
}