题目: 给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。 题目链接
我的JavaScript解法
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
const stack = []
for(item of s) {
if(['(', '{', '['].includes(item)) {
stack.push(item)
} else {
if (stack.length > 0 && peer[item] == stack[stack.length-1]) {
stack.pop();
} else {
return false;
}
}
}
return !stack.length
};
const peer = {
'}': '{',
')': '(',
']': '['
}
解析: 利用数据结构栈来解决
- 时间复杂度:
- 空间复杂度: