Skip to content

Instantly share code, notes, and snippets.

@elevenrax
Created February 8, 2018 09:04
Show Gist options
  • Save elevenrax/bbdcd4bc2682943e65c5d0855474e3b5 to your computer and use it in GitHub Desktop.
Save elevenrax/bbdcd4bc2682943e65c5d0855474e3b5 to your computer and use it in GitHub Desktop.
Work out whether brackets {[()]} are balanced
import java.util.Stack;
public class Main {
public static void main(String[] args) {
String s = "[]{}[][]";
boolean b = isBalanced(s);
System.out.println(b);
String s2 = "[]{}[}][]";
boolean b2 = isBalanced(s2);
System.out.println(b2);
String s3 = "{{})";
boolean b3 = isBalanced(s3);
System.out.println(b3);
String s4 = "{{{{((]";
boolean b4 = isBalanced(s4);
System.out.println(b4);
}
public static boolean isBalanced(String s) {
Stack<Character> balanceStack = new Stack<>();
for(char token : s.toCharArray()) {
// Add Opening Tokens to a Stack
if( token == '{' || token == '[' || token == '(' ) {
balanceStack.push(token);
}
// Inspect relevant closing token
else if (!balanceStack.isEmpty()) {
char open = balanceStack.pop();
// Check of mismatch between closing token
// and token on top of stack
if (token == '}') {
if (open != '{') {
return false;
}
}
else if (token == ']') {
if (open != '[') {
return false;
}
}
else if (token == ')') {
if (open != '(') {
return false;
}
}
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment