- 定义左括号key 右括号value 的map 和 一个stack
- 遍历字符串每次将左括号推入stack中,遇到右括号则从stack取出,通过map进行比对
- 如果比对失败则返回false
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
const stack = []
const stringMap = {
'(':')',
'[':']',
'{':'}'
}
for(let key of s){
if(stringMap[key]){
stack.push(stringMap[key])
}else{
if(stack.pop() !== key) return false
}
}
return !stack.length
};
时间复杂度:
- 对字符串进行了一次遍历所以是 O(n)
**
空间复杂度:
- 需要一个stack来存放左括号 ,所以是 O(n)