-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbalanced.cpp
51 lines (46 loc) · 985 Bytes
/
balanced.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
#include "balanced.h"
// Returns true if the parenthesis,
// square brackets, and curly braces
// in text are balanced
bool isBalanced(const std::string &text){
char c;
char fromStack;
std::stack<char> unmatched;
for(int i=0; i<text.size(); i++){
c = text[i];
switch(c){
case '[':
unmatched.push(c);
break;
case '{':
unmatched.push(c);
break;
case '(':
unmatched.push(c);
break;
case ']':
if(unmatched.empty() || unmatched.top() != '['){
return false;
}
unmatched.pop();
break;
case '}':
if(unmatched.empty() || unmatched.top() != '{'){
return false;
}
unmatched.pop();
break;
case ')':
if(unmatched.empty() || unmatched.top() != '('){
return false;
}
unmatched.pop();
break;
}
}
if(!unmatched.empty())
{
return false;
}
return true;
}