Skip to content
This repository was archived by the owner on Oct 24, 2020. It is now read-only.

Commit 136e586

Browse files
authored
Merge pull request kothariji#121 from MrTwinkleSharma/master
Application of Stack (Balanced Brackets)
2 parents 7e64734 + d7ac013 commit 136e586

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
//This ALgorithm checks whether all the brackets of string are balanced or not
5+
//Go to Hackerrank "Balanced Brackets" Question to see more description
6+
7+
// Complete the isBalanced function below.
8+
string isBalanced(string text) {
9+
//creating a stack to store opening brackets only
10+
stack <char> opening_brackets_stack;
11+
12+
//Looping till string end
13+
for (int position = 0; position < text.length(); ++position) {
14+
char next = text[position];
15+
//storing the character in a next named char
16+
17+
//if it is open bracket then simpy push it in stack
18+
if (next == '(' || next == '[' || next == '{') {
19+
opening_brackets_stack.push(next);
20+
}
21+
22+
//if closed then check two conditions
23+
if (next == ')' || next == ']' || next == '}') {
24+
25+
char last;
26+
//if the stack is empty means brackets will be unbalanced if not then it get the last bracket of stack
27+
if(!opening_brackets_stack.empty())
28+
{
29+
last = opening_brackets_stack.top();
30+
}
31+
else return "NO";
32+
33+
//if last matches with next then pop that opening bracket otherwise return NO
34+
if ((last == '(' && next== ')') || (last == '[' && next == ']') || (last == '{' && next== '}'))
35+
{
36+
opening_brackets_stack.pop();
37+
continue;
38+
}
39+
else
40+
return "NO";
41+
}
42+
}
43+
44+
//At the end if nothing is returned from loop then now check whether the stack is empty or not if yes then it means, string was balanced.
45+
if(opening_brackets_stack.empty())
46+
return "YES";
47+
else
48+
return "NO";
49+
}
50+
51+
int main()
52+
{
53+
ofstream fout(getenv("OUTPUT_PATH"));
54+
55+
int t;
56+
cin >> t;
57+
cin.ignore(numeric_limits<streamsize>::max(), '\n');
58+
59+
for (int t_itr = 0; t_itr < t; t_itr++) {
60+
string s;
61+
getline(cin, s);
62+
63+
string result = isBalanced(s);
64+
65+
fout << result << "\n";
66+
}
67+
68+
fout.close();
69+
70+
return 0;
71+
}

0 commit comments

Comments
 (0)