forked from aswinkumarrk/data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBalancedParentheses.java
More file actions
46 lines (38 loc) · 1.42 KB
/
BalancedParentheses.java
File metadata and controls
46 lines (38 loc) · 1.42 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
package com.geeksforgeeks.stack;
import java.util.*;
public class BalancedParentheses {
private static List<Character> OpeningParentheses = Arrays.asList('(', '{', '[');
private static Map<Character, Character> matchingParentheses = new HashMap<>();
static {
matchingParentheses.put(')', '(');
matchingParentheses.put(']', '[');
matchingParentheses.put('}', '{');
}
public static void main(String[] args) {
String[] testCases = new String[]{"{[()]}", "{[(])}", "{{[[(())]]}}", "[()]{}{[()()]()}", "[(])", "[(]()"};
for (String s : testCases) {
System.out.println(s + " <<::::>> " + areParenthesesBalanced(s));
}
}
public static boolean isOpeningParentheses(char c) {
return OpeningParentheses.contains(c);
}
public static Character getMatchingParentheses(Character c) {
return matchingParentheses.get(c);
}
public static boolean areParenthesesBalanced(String str) {
boolean _result = true;
Stack<Character> stack = new Stack<>();
char[] input = str.toCharArray();
for (char c : input) {
if (isOpeningParentheses(c)) {
stack.push(c);
} else {
if (stack.isEmpty() || stack.pop() != getMatchingParentheses(c)) {
return false;
}
}
}
return stack.isEmpty() ? true : false;
}
}