Code challenge

private static final Map brackets = new HashMap() {{
put('(', ')');
put('{', '}');
put('[', ']');
}};

static boolean isBracket(char c) {
return isLeft(c) || isRight(c);
}

static boolean isLeft(char c) {
return brackets.keySet().contains(c);
}

static boolean isRight(char c) {
return brackets.values().contains(c);
}

static boolean areOpposite(char a, char b) {
return Objects.equals(brackets.get(a), b);
}

static boolean canFollow(char c, char prev) {
if (isRight(prev)) return true; // anything can follow and opening bracket
return isLeft(c) || areOpposite(prev, c); // a right paren can not follow a left square bracket
}

static boolean balanced(String str) {
Stack stack = new Stack(); // only push never pop

int openBrackets = 0;
for (int i = 0; i < str.length(); i++) {
final char c = str.charAt(i);
if (!isBracket(c)) continue;
if (isLeft(c)) openBrackets++;
if (isRight(c)) openBrackets--;

if (stack.empty()) {
stack.push(c);
continue;
}

char prev = stack.peek();
if (!canFollow(c, prev)) return false;


stack.push(c);
}
return openBrackets == 0;
}


this is probably the only correct solution ITT

>C
No one uses this @ facebook.

You responded to the wrong user but also no shit

Based and erlangpilled.

No time to code, but I figure you'd push the opening symbols ( { [ on a stack, and if a closing one appears ) } ] you pop the top of the stack.

If it doesn't match the same type it's not balanced, right?

you cant pop because the opening bracket could be anywhere in the stack

That was my solution too fren

import balanced.isBalanced as myFunc

EXAMPLE = "(()()[])"

print(myFunc(EXAMPLE))

just realized that the single counter allows a square bracket to close a paren which makes "( [ ] ]" return true

idiot