Create a function that will evaluate if a given expression has balanced parentheses using stacks

Technology CommunityCategory: JavaScriptCreate a function that will evaluate if a given expression has balanced parentheses using stacks
VietMX Staff asked 3 years ago

In this example, we will only consider {} as valid parentheses {}{} would be considered balancing. {{{}} is not balanced.

var expression = "{{}}{}{}"
var expressionFalse = "{}{{}";

isBalanced(expression); // true
isBalanced(expressionFalse); // false
isBalanced(""); // true

function isBalanced(expression) {
  var checkString = expression;
  var stack = [];

  // If empty, parentheses are technically balanced
  if (checkString.length <= 0) return true;

  for (var i = 0; i < checkString.length; i++) {
    if(checkString[i] === '{') {
      stack.push(checkString[i]);
    } else if (checkString[i] === '}') {
      // Pop on an empty array is undefined
      if (stack.length > 0) {
        stack.pop();
      } else {
        return false;
      }
    }
  }

  // If the array is not empty, it is not balanced
  if (stack.pop()) return false;
  return true;
}