Code Corner: Balancing Brackets
Join the DZone community and get the full member experience.
Join For Free
given a sentence or formula containing square brackets, curly braces and brackets, write an algorithm to determine if it is balanced.
this question has been around for a long time but often candidates can struggle with it due to having limited data structures experience. there’s a number of possible ways of coming up with a solution, but here’s the best i’m aware of.
at its purest form this is a matching exercise. we obviously need to loop through the characters in the sentence. for efficiency we want to only iterate through it once, which rules out the option of taking each character and then trying to find it’s partner from the opposite end (which will result in multiple iterations). but how do we keep track of what we have seen, and in what order?
in day to day work, people generally spend most of their time with lists and maps. there’s a ton of other collections in the java universe but people don’t get experience with them which is why this can be so tricky. the data structure we’re looking for here is a stack. stacks are lifo, last in first out. that means whichever element i most recently added will be removed first. this is perfect for this exercise, as it means as i go through i can pop opening brackets onto the stack, and if i find a closing brace i then can compare it to whatever is on top of the stack. if it matches then we’re happy, else we know we’re unbalanced.
//pseudocode loop through characters of string if(this character is an opening brace) push onto stack if(this character is a closing brace) pop from stack. if it isn't the matching brace, return false
if you had figured out this far then well done. you know how to use stacks and how to apply it to this problem which is the main test as part of this question. there are a couple of hazards to avoid when implementing though.
firstly, although java does have a stack collection you shouldn’t use it. even oracle’s own documentation says to avoid it in favour of dequeue. a dequeue is a double ended queue and has functionality to support lifo and fifo (first in first out) functionality.
secondly, it’s really easy to write ugly code for this. most the implementations you’ll find on line have a ton of if statements; there’s a particularly horrible implantation from princeton you can see the source for here . big if statements are a terrible practice; they’re very difficult to read and understand. your code combined with your tests should be your documentation; if you feel the need to write comments then 95% of the time you need to break your code down and make it simpler. hopefully you can apply your knowledge to come up with something a bit more obvious!
import org.junit.test; import static org.hamcrest.corematchers.is; import static org.hamcrest.matcherassert.assertthat; public class stackformulabalancetest { private stackformulabalance stackformulabalance; @test public void emptystringisbalanced() throws exception { stackformulabalance = new stackformulabalance(); assertthat(stackformulabalance.balance(""), is(true)); } @test public void lotsofnestedbracketsbutbalancedreturnstrue() throws exception { stackformulabalance = new stackformulabalance(); assertthat(stackformulabalance.balance("([hell{} t(h(e[r]e))]boom)"), is(true)); } @test public void correctnumberofclosingbracketsbutinwrongorderreturnsfalse() throws exception { stackformulabalance = new stackformulabalance(); assertthat(stackformulabalance.balance("(a[b{c)d]e}"), is(false)); } @test public void onlyhasclosedbracesreturnsfalse() throws exception { stackformulabalance = new stackformulabalance(); assertthat(stackformulabalance.balance("}])"), is(false)); } @test public void correctbalancingbutwithmoreopeningbracketsreturnsfalse() throws exception { stackformulabalance = new stackformulabalance(); assertthat(stackformulabalance.balance("({}"), is(false)); } } import java.util.arraydeque; import java.util.deque; import java.util.hashmap; import java.util.map; public class stackformulabalance { map<character, character> brackets = new hashmap<character, character>() {{ put('{', '}'); put('(', ')'); put('[', ']'); }}; public boolean balance(string tobalance) { deque<character> bracketsstack = new arraydeque<character>(); for (int i = 0; i < tobalance.length(); i++) { char currentchar = tobalance.charat(i); if (characterisopenbracket(currentchar)) { bracketsstack.push(currentchar); } else if (characterisaclosingbracket(currentchar) && closingbracketmatcheslastopeningbracket(bracketsstack, currentchar)) { return false; } } return bracketsstack.isempty; } private boolean closingbracketmatcheslastopeningbracket(deque<character> bracketsstack, char currentchar) { return bracketsstack.size() == 0 || !brackets.get(bracketsstack.pop()).equals(currentchar); } private boolean characterisaclosingbracket(char currentchar) { return brackets.values().contains(currentchar); } private boolean characterisopenbracket(char currentchar) { return brackets.containskey(currentchar); } }
the private methods could be inlined if you’re that way inclined, but by pulling them out and naming them well we can make our algorithm clear. it reads very similarly to the pseudocode.
what do you think? do you have a better implementation or other suggestions? let me know!
Published at DZone with permission of Sam Atkinson, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments