Skip to content

Commit 5e55c46

Browse files
authored
Create Stack-Brackets Balanced
1 parent a81972d commit 5e55c46

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

Stack-Brackets Balanced

+80
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
For a given a string expression containing only round brackets or parentheses, check if they are balanced or not. Brackets are said to be balanced if the bracket which opens last, closes first.
2+
Example:
3+
Expression: (()())
4+
Since all the opening brackets have their corresponding closing brackets, we say it is balanced and hence the output will be, 'true'.
5+
You need to return a boolean value indicating whether the expression is balanced or not.
6+
Note:
7+
The input expression will not contain spaces in between.
8+
Input Format:
9+
The first and the only line of input contains a string expression without any spaces in between.
10+
Output Format:
11+
The only line of output prints 'true' or 'false'.
12+
Note:
13+
You don't have to print anything explicitly. It has been taken care of. Just implement the function.
14+
Constraints:
15+
1 <= N <= 10^7
16+
Where N is the length of the expression.
17+
18+
Time Limit: 1sec
19+
Sample Input 1 :
20+
(()()())
21+
Sample Output 1 :
22+
true
23+
Sample Input 2 :
24+
()()(()
25+
Sample Output 2 :
26+
false
27+
Explanation to Sample Input 2:
28+
The initial two pairs of brackets are balanced. But when you see, the opening bracket at the fourth index doesn't have its corresponding closing bracket which makes it imbalanced and in turn, making the whole expression imbalanced. Hence the output prints 'false'.
29+
30+
***********************************************************Code*****************************************************
31+
import java.util.Stack;
32+
public class Solution {
33+
34+
public static boolean isBalanced(String expression) {
35+
36+
Stack<Character> stack=new Stack<Character>();
37+
for (int j=0;j<expression.length();j++)
38+
{
39+
char i=expression.charAt(j);
40+
if (i=='[' || i=='{' || i=='(')
41+
{
42+
stack.push(i);
43+
}
44+
else if(i==']' || i=='}' || i==')')
45+
{
46+
if (stack.isEmpty())
47+
return false;
48+
49+
else
50+
{
51+
if (i==']')
52+
{
53+
if (stack.peek()!='[')
54+
return false;
55+
else
56+
stack.pop();
57+
}
58+
59+
else if (i=='}')
60+
{
61+
if (stack.peek()!='{')
62+
return false;
63+
else
64+
stack.pop();
65+
}
66+
67+
else if (i==')')
68+
{
69+
if (stack.peek()!='(')
70+
return false;
71+
else
72+
stack.pop();
73+
}
74+
}
75+
}
76+
77+
}
78+
return stack.isEmpty();
79+
}
80+
}

0 commit comments

Comments
 (0)