24
loading...
This website collects cookies to deliver better user experience
import java.util.*;
class BalancedBrackets {
// We need to store all opening brackets in a list
// and closing brackets in another.
// How do we make sure an opening bracket
// relates with another (such as '<' relates to '>')?
// The way is to put them in the same index in the two lists
// although they are in different lists.
private final List < Character > leftBrackets = Arrays.asList('(', '[', '{', '<');
private final List < Character > rightBrackets = Arrays.asList(')', ']', '}', '>');
public boolean balancedBrackets(String str) {
Stack <Character> stack = new Stack <> ();
for (char ch: str.toCharArray()) {
// if current character is a left bracket, push it to the stack
if (isLeftBracket(ch))
stack.push(ch);
if (isRightBracket(ch)) {
// If current character is a right bracket, don't push it to the
// stack rather pop an existing item in the stack and compare if
// these two brackets are related to each other. Before that, if
// the stack is empty and the current character is a closing
// bracket, we don't need to do a lot of thinking rather we can
// just return false because for every closing bracket, there must
// be an opening bracket waiting in the stack to be popped.
// Therefore, empty stack means things went wrong, so return false
// immediately.
if (stack.empty())
return false;
var top = stack.pop();
if (!bracketsMatch(top, ch))
return false;
}
}
return stack.empty();
}
private boolean isLeftBracket(char ch) {
return leftBrackets.contains(ch);
}
private boolean isRightBracket(char ch) {
return rightBrackets.contains(ch);
}
// This method checks if an opening bracket matches with another
// (for example, '<' matches with '>', '(' matches with ')', and
// so on). For this method to work, we need to make sure each
// index in the two lists hold the brackets of same type. For
// example, at index 2 in first list, if the element is '<', then
// then in index 2 in second list the element must be matching, in
// this case '>'.
private boolean bracketsMatch(char left, char right) {
return leftBrackets.indexOf(left) == rightBrackets.indexOf(right);
}
}