分页: 1 / 1

[JS][算法]通过"栈"判断多重分级括号是否配对

发表于 : 2017年09月06日 16:47
523066680
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(); };
}

Re: [JS][算法]通过"栈"判断多重分级括号是否配对

发表于 : 2018年11月04日 21:45
rubyish
3Q~~ :happy :happy