Last active
August 18, 2017 05:59
-
-
Save ivanursul/207c217330de48791fc06c57a29d26c2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.Stack; | |
public class BracketBalancing { | |
private final String expression; | |
public BracketBalancing(String expression) { | |
this.expression = expression; | |
} | |
public boolean isBalanced() { | |
Stack<Character> bracketsStack = new Stack<>(); | |
for (int i = 0; i < expression.length(); i++) { | |
if (!isBracket(expression.charAt(i))) { | |
continue; | |
} | |
if (isStartingBracket(i)) { | |
bracketsStack.push(expression.charAt(i)); | |
} else if (isClosingBracket(i) && !bracketsStack.isEmpty()) { | |
Character possibleBracket = bracketsStack.pop(); | |
if (!isOppositeBracket(possibleBracket, expression.charAt(i))) { | |
return false; | |
} | |
} else if (isClosingBracket(i) && bracketsStack.isEmpty()) { | |
// not balanced, because there can't be a closing bracket | |
// with no opening bracket in the stack | |
return false; | |
} | |
} | |
if (!bracketsStack.isEmpty()) { | |
return false; | |
} | |
return true; | |
} | |
private boolean isBracket(char currentCharacter) { | |
return Arrays.asList('[', '(', '{', ']', ')', '}').contains(currentCharacter); | |
} | |
private boolean isOppositeBracket(char poppedBracket, char currentBracket) { | |
if (poppedBracket == '{' && currentBracket == '}') { | |
return true; | |
} else if (poppedBracket == '[' && currentBracket == ']') { | |
return true; | |
} else if (poppedBracket == '(' && currentBracket == ')') { | |
return true; | |
} else { | |
return false; | |
} | |
} | |
private boolean isStartingBracket(int i) { | |
return Arrays.asList('{', '[', '(').contains(expression.charAt(i)); | |
} | |
private boolean isClosingBracket(int i) { | |
return Arrays.asList('}', ']', ')').contains(expression.charAt(i)); | |
} | |
public static void main(String[] args) { | |
String expression1 = "[({})]"; | |
System.out.println(expression1 + ":" + new BracketBalancing(expression1).isBalanced()); | |
String expression2 = "[([)"; | |
System.out.println(expression2 + ":" + new BracketBalancing(expression2).isBalanced()); | |
String expression3 = "[()]{}{[()()]()}"; | |
System.out.println(expression3 + ":" + new BracketBalancing(expression3).isBalanced()); | |
String expression4 = "[()]{}{[(hello world ^ 2)()]()}"; | |
System.out.println(expression4 + ":" + new BracketBalancing(expression4).isBalanced()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment