-
Notifications
You must be signed in to change notification settings - Fork 0
Closed
Description
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"
输出: true
解法:
1 建立开始结束关系。
2利用栈的先进后出特点。
3 遍历每一个字符,如果与栈顶元素匹配,则出栈,不匹配则进栈;
最后为空栈说明是合法的。
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
let rs=false;
let key={
'(':')',
'{':'}',
'[':']'
};
if(s.length==0){
rs=true;
}
let stack=[];
for(let i=0;i<s.length;i++){
let char=s[i];
if(char===key[stack[stack.length-1]]){ // 确立关系
stack.pop();
}else{
stack.push(char);
}
}
if(stack.length==0){
rs=true;
}
return rs;
};
Metadata
Metadata
Assignees
Labels
No labels