-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathBalancedBrackets.java
More file actions
70 lines (55 loc) · 1.82 KB
/
BalancedBrackets.java
File metadata and controls
70 lines (55 loc) · 1.82 KB
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
63
64
65
66
67
68
69
70
import java.util.*;
class BalancedBrackets{
public static String balancedBracket(String exp){
Stack<Character> s = new Stack<Character>();
int flag =0;
for(int i=0; i<exp.length(); i++)
{
char ch = exp.charAt(i);
/*If opening bracket is encountered then it is pushed in the stack */
if((ch=='(') || (ch=='[') || (ch=='{'))
{
s.push(ch);
continue;
}
/*If closing bracket is encountered then if its corresponding pair bracket is not at top of stack then value of flag is changed and loop is terminated */
if((ch==')') || (ch==']') || (ch=='}'))
{
if(ch == ')' && s.peek() != '(')
{
flag =1;
break;
}
if(ch == ']' && s.peek() != '[')
{
flag =1;
break;
}
if(ch == '}' && s.peek() != '{')
{
flag =1;
break;
}
}
}
String st;
/*Check flag value to know whether loop terminated normally or abruptly in between */
if(flag == 0)
{
st = "balanced";
}
else
{
st = "not balanced";
}
return st;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the expression : ");
String s = sc.nextLine();
String ans = balancedBracket(s);
System.out.println("Given expression is " + ans + " in terms of brackets");
sc.close();
}
}