forked from hacktoberfest2k20/DataStructures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbalanced_brackets.cpp
More file actions
54 lines (50 loc) · 947 Bytes
/
balanced_brackets.cpp
File metadata and controls
54 lines (50 loc) · 947 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
49
50
51
52
53
54
/*
Problem: To check if given bracket sequence is balanced or not.
Complexity: O(N)
*/
#include <iostream>
using namespace std;
int main()
{
//input a string with only '(' or ')' characters
string s;
cin >> s;
int var = 1;
if (s[0] == ')')
{
cout << "Not balanced\n"; //since a balanced sequence cannot start from ')'
return 0;
}
for (int i = 1; i < s.length(); i++)
{
if (s[i] == '(')
{
var++;
}
else if (s[i] == ')')
{
var--;
}
else
{
cout << "Illeagal input string.\n";
return 0;
}
//if at any point var<0 => the string uptil now has more ')'s than '(' and hence cannot be balanced.
if (var < 0)
{
cout << "Not balanced\n";
return 0;
}
}
if (var != 0)
{
cout << "Not balanced\n";
//this implies that number of '(' != number of ')' hence sequence is not balanced.
}
else
{
cout << "Balanced sequence\n";
}
return 0;
}