leetcode20.有效的括号
题目描述:
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
示例 1:
输入:s = “()”
输出:true
示例 2:
输入:s = “()[]{}”
输出:true
示例 3:
输入:s = “(]”
输出:false
示例 4:
输入:s = “([)]”
输出:false
示例 5:
输入:s = “{[]}”
输出:true
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
//如果字符串长度为奇数,直接返回false
if(s.length % 2 == 1) { return false }
let stack = [];
for(let i = 0; i < s.length; i++) {
let c = s[i];
//如果为左括号,推入栈
if(c == '('|| c =='{'||c=='[') {
stack.push(c)
} else {
//如果为右括号,且与左括号匹配,推出栈
if(stack[stack.length - 1] == '(' && c == ')') {
stack.pop();
} else if((stack[stack.length - 1] == '[' && c == ']')) {
stack.pop();
} else if((stack[stack.length - 1] == '{' && c == '}')) {
stack.pop();
} else {
//如果为右括号,且与左括号不匹配,返回false
return false
}
}
}
//字符串遍历完毕,数组为空,返回true,否则返回false
if(stack.length == 0) {
return true
} else {
return false
}
};