We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
functionis_balanced(expression){conststack=[];constbrackets={"{":"}","[":"]","(":")"};for(leti=0;i<expression.length;i++){constb=expression[i];if(brackets[b]!==undefined)stack.push(brackets[b]);// it's an opening bracket, so push the corresponding closing one into the stackelse{if(stack.length===0||b!==stack[stack.length-1])returnfalse;stack.pop();}}returnstack.length===0;}
If you write a simple hash map like the brackets object, you don't need to explicitly check if a given bracket is a closing one by using ifs. Just see if the hash map has the desired key (in this case an opening bracket). If so, push the value into the stack (in this case a closing bracket). The rest is pretty much the same.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Stacks: Balanced Brackets
You are viewing a single comment's thread. Return to all comments →
This is my JavaScript version of this solution:
If you write a simple hash map like the
brackets
object, you don't need to explicitly check if a given bracket is a closing one by usingif
s. Just see if the hash map has the desired key (in this case an opening bracket). If so, push the value into the stack (in this case a closing bracket). The rest is pretty much the same.