-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjava-stack.java
43 lines (34 loc) · 1.22 KB
/
java-stack.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
import java.util.*;
class Solution {
private static boolean isBalance(String input) {
Stack<String> stack = new Stack();
for (int i = 0; i < input.length(); i++) {
String element = input.substring(i, i + 1);
if (element.equals("{") || element.equals("(") || element.equals("[")) {
stack.push(element);
} else {
String topElement = "";
try {
topElement = stack.peek();
} catch (EmptyStackException e) {
return false;
}
if (element.equals("}") && topElement.equals("{")) {
stack.pop();
} else if (element.equals(")") && topElement.equals("(")) {
stack.pop();
} else if (element.equals("]") && topElement.equals("[")) {
stack.pop();
}
}
}
return stack.size() == 0;
}
public static void main(String[] argh) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String input = sc.next();
System.out.println(isBalance(input) ? "true" : "false");
}
}
}