-
-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathBalanceParanthesis.java
56 lines (41 loc) · 1.24 KB
/
BalanceParanthesis.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
package lesson13;
import java.util.Stack;
/*
* @author Nirmal Silwal
* @contact nsilwal@miu.edu
*/
public class BalanceParanthesis {
private static boolean validParanthesis(String expression) {
if (expression.length() == 0)
return true;
Stack<Character> stack = new Stack<>();
boolean valid = false;
for (Character ch : expression.toCharArray()) {
if (ch == '(' || ch == '{' || ch == '[') {
stack.push(ch);
}
if (ch == ')' || ch == '}' || ch == ']') {
if (stack.isEmpty())
return false; // nothing to match
char topchar = stack.pop();
if ((topchar == '(' && ch == ')') || (topchar == '{' && ch == '}') || (topchar == '[' && ch == ']'))
valid = true;
else
return false;
}
}
if (!stack.isEmpty()) // still there is some character in the Stack at the end
valid = false;
return valid;
}
public static void main(String[] args) {
String expression = "(a+b)-{c/d}";
System.out.println(validParanthesis(expression));
System.out.println(validParanthesis("(a*b(a-b))"));
System.out.println(validParanthesis("(a*b](a-b)"));
System.out.println(validParanthesis("[A+25*(Y*(B+C-X-K/D)*(E+13)]+M"));
// from LC judge
String s = "([]){";
System.out.println(validParanthesis(s));
}
}