题目:
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。 ```javascript 示例 1:
输入:s = “()” 输出:true 示例 2:
输入:s = “()[]{}” 输出:true 示例 3:
输入:s = “(]” 输出:false 示例 4:
输入:s = “([)]” 输出:false 示例 5:
输入:s = “{[]}” 输出:true
<a name="5srQd"></a># 方法一:```javascriptvar isValid = function(s) {while(s.length){var temp = s;s = s.replace("()","");s = s.replace("{}","");s = s.replace("[]","");if(s==temp)return false;}return true;};
方法二:
var isValid = function(s) {
var map = {
"(":")",
"[":"]",
"{":"}"
}
var leftchar = [];
for(var ch of s){
if(ch in map) leftchar.push(ch);
else if(ch != map[leftchar.pop()]) return false;
}
return !leftchar.length;
};
方法三:
var isValid = function(s) {
const stack = [];
var len = s.length;
for(let i=0;i<len;i++){
const c=s[i];
if(c=='('||c=='{'||c=='['){
stack.push(c);
}else{
if(stack.length==0){
return false;
}
const top = stack[stack.length-1];
if(c==')'&&top=='('||c==']'&&top=='['||c=='}'&&top=='{'){
stack.pop()
}else{
return false;
}
}
}
return stack.length==0
};
