Code: [show] | [select all]
function matches(open, close)
{
var opens = "([{",
closers = ")]}";
return opens.indexOf(open) == closers.indexOf(close);
}
function parenthesesChecker(symbols)
{
var stack = new Stack();
var balanced = true;
var index = 0;
var symbol, top;
while (index < symbols.length && balanced)
{
symbol = symbols.charAt(index);
if (symbol == '(' || symbol == '[' || symbol == '{')
{
stack.push(symbol);
}
else
{
if (stack.isEmpty())
{
balanced = false;
}
else
{
top = stack.pop();
if ( !matches(top, symbol) )
{
balanced = false;
}
}
}
index++;
}
if (balanced && stack.isEmpty())
{
return true;
}
return false;
}
console.log(parenthesesChecker('{{([][])}()}'));
console.log(parenthesesChecker('[{()]'));
function Stack()
{
var items = [];
this.push = function(element) { items.push(element); };
this.pop = function() { return items.pop(); };
this.peek = function() { return items[items.length-1]; };
this.isEmpty = function() { return items.length == 0; };
this.size = function() { return items.length; };
this.clear = function() { items = []; };
this.print = function() { console.log(items.toString()); };
this.toString = function() { return items.toString(); };
}