-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathBalancedParentheses.java
71 lines (61 loc) · 1.14 KB
/
BalancedParentheses.java
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
71
/*
Name : Elenaires
College Name : Curtin
Year/Department : I/Comp Sci
E-Mail Id : 15650635@curtin.edu.au
*/
import java.util.*;
public class BalancedParentheses {
public static void main(String[] args)
{
String s = "{(){}{{)}}}";
System.out.println(balance(s));
}
public static boolean balance(String expression)
{
if(expression.length() == 0)
{
return true;
}
if(expression.length() % 2 != 0)
{
return false;
}
Stack<Character> stack = new Stack<>();
char c;
for(int i = 0; i < expression.length(); i++)
{
c = expression.charAt(i);
// opening braces
if(c == '(' || c == '[' || c == '{')
{
stack.push(c);
}
// closing braces
else
{
if(!stack.isEmpty())
{
char top = stack.peek();
if(isMatching(top, c))
{
stack.pop();
}
else
{
return false;
}
}
else
{
return false;
}
}
}
return stack.isEmpty();
}
private static boolean isMatching(char top, char current)
{
return (top == '(' && current == ')') ? true : (top == '[' && current == ']') ? true : (top == '{' && current == '}') ? true : false;
}
}