-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbalanced-paranthesis.cpp
62 lines (55 loc) · 1.75 KB
/
balanced-paranthesis.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
// A common problem for compilers and text editors is determining whether the
// parentheses in a string are balanced and properly nested. For example, the
// string
// ((())())() contains properly nested pairs of parentheses, which the strings
// )()( and
// ()) do not. Give an algorithm that returns true if a string contains properly
// nested and balanced parentheses, and false if otherwise. For full credit,
// identify the position of the first offending parenthesis if the string is not
// properly nested and balanced.
#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool isBalanced(std::string S) {
std::stack<char> brackets;
char x;
for (int i = 0; i < S.length(); ++i) {
if (S[i] == '(') {
brackets.push(S[i]);
continue;
}
if (brackets.empty())
return false;
else if (S[i] == ')') {
if (brackets.top() == '(') {
brackets.pop();
continue;
} else
break;
}
}
return (bool)brackets.empty();
}
int main(int argc, char const *argv[]) {
string S;
S = "((())())()";
std::cout << S << " is " << (isBalanced(S) ? "Balanced" : "Not Balanced")
<< std::endl;
S = "()";
std::cout << S << " is " << (isBalanced(S) ? "Balanced" : "Not Balanced")
<< std::endl;
S = "(";
std::cout << S << " is " << (isBalanced(S) ? "Balanced" : "Not Balanced")
<< std::endl;
S = ")()(";
std::cout << S << " is " << (isBalanced(S) ? "Balanced" : "Not Balanced")
<< std::endl;
S = "((()))";
std::cout << S << " is " << (isBalanced(S) ? "Balanced" : "Not Balanced")
<< std::endl;
S = "((())))";
std::cout << S << " is " << (isBalanced(S) ? "Balanced" : "Not Balanced")
<< std::endl;
return 0;
}