您的位置:首页 > Web前端 > JavaScript

[LeetCode][JavaScript]Valid Parentheses

2015-05-17 16:44 155 查看
Valid Parentheses

Given a string containing just the characters
'('
,
')'
,
'{'
,
'}'
,
'['
and
']'
, determine if the input string is valid.

The brackets must close in the correct order,
"()"
and
"()[]{}"
are all valid but
"(]"
and
"([)]"
are not.

https://leetcode.com/problems/valid-parentheses/

水题好愉快。

/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
var stack = [];
function brackets(left, right){
if(left === '(' && right === ')'){
return true;
}else if(left === '[' && right === ']'){
return true;
}else if(left === '{' && right === '}'){
return true;
}
return false;
}
var top = null;
for(var i in s){
if(/[\({\[]/.test(s[i])){
stack.push(s[i]);
}else{
if(stack.length > 0){
top = stack.pop();
if(!brackets(top, s[i])){
return false;
}
}else{
return false;
}
}
}

if(stack.length !== 0){
return false;
}
return true;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: