Given a Balanced Parenthesis problem.
"Balanced Parenthesis
Create a program that checks if in a given string expression all the parenthesis are balanced.
For Example:
(test) - valid
(no() - invalid
()(()) - valid
(123(456)(7))( - invalid
(val()id) - valid
Also, take into account the "\" escape sequences:
(nope\) - invalid
(v\(al) - valid
Too easy? Try doing the same for [] and {} and <>.
(The description from Sololearn application)"
This is my solution. Do you have any advice? Is it clear enough?
import java.util.Stack;
public class BalancedParenthesis {
private static final Stack<Character> STACK = new Stack<>();
private static final String BRACELETS = "({[<)}]>";
private static final int SEPARATOR = BRACELETS.length() / 2;
private static final char BACKSLASH = '\\';
public static boolean isBalanced(String str) {
int index; char ch;
STACK.clear();
for (int pos = 0; pos < str.length(); pos++) {
ch = str.charAt(pos);
if (ch == BACKSLASH) {
pos ++;
continue ; }
index = BRACELETS.indexOf(ch);
if (isBaceletFind(index)) {
if (isOpenBracelet(index)) STACK.push(ch);
else if (isPopable(index)) STACK.pop();
else return false; }
}
return STACK.empty();
}
private static boolean isPopable(int index) {
return !STACK.empty() && STACK.peek() == BRACELETS.charAt(index - SEPARATOR);
}
private static boolean isBaceletFind(int index) {
return index != -1;
}
private static boolean isOpenBracelet(int index) {
return index < SEPARATOR;
}
public static void checkBalance(String str) {
System.out.print("\"" + str + "\" is");
System.out.println((isBalanced(str) ? "" : " not") + " balanced");
}
public static void main(String[] args) {
checkBalance("");
checkBalance("\\");
checkBalance("\\(");
checkBalance("(({[<>]}))");
checkBalance("))");
checkBalance("(({[<(>]}))");
checkBalance("(({[<\\(>]}))");
}
}