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

回复
头像
523066680
Administrator
Administrator
帖子: 573
注册时间: 2016年07月19日 12:14
联系:

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

帖子 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(); };
}
头像
rubyish
渐入佳境
渐入佳境
帖子: 52
注册时间: 2018年04月23日 09:58
联系:

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

帖子 rubyish »

3Q~~ :happy :happy
$_
回复

在线用户

正浏览此版面之用户: 没有注册用户 和 1 访客