forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBalancedParentheses.java
More file actions
45 lines (41 loc) · 1.26 KB
/
BalancedParentheses.java
File metadata and controls
45 lines (41 loc) · 1.26 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
package com.examplehub.datastructures.stack;
import java.util.Stack;
public class BalancedParentheses {
/**
* Test if a parentheses expression
*
* @param parenthesesExpr the parentheses expression
* @return {@code true} if given parentheses expression is balanced.å
*/
public static boolean isBalanced(String parenthesesExpr) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < parenthesesExpr.length(); i++) {
switch (parenthesesExpr.charAt(i)) {
case '(':
case '[':
case '{':
stack.push(parenthesesExpr.charAt(i));
break;
case ')':
case ']':
case '}':
if (stack.isEmpty() || !isPaired(stack.pop(), parenthesesExpr.charAt(i))) {
return false;
}
}
}
return stack.isEmpty();
}
/**
* Test if left bracket and right bracket is paired.
*
* @param leftBracket the left bracket.
* @param rightBracket the right bracket.
* @return {@code true} if two brackets are paired.
*/
public static boolean isPaired(char leftBracket, char rightBracket) {
return leftBracket == '(' && rightBracket == ')'
|| leftBracket == '[' && rightBracket == ']'
|| leftBracket == '{' && rightBracket == '}';
}
}