feat: 有效的括号(20)
This commit is contained in:
parent
2f5bb15dfe
commit
d56b6bbee1
52
leetcode/简单/有效的括号.js
Normal file
52
leetcode/简单/有效的括号.js
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
/*
|
||||||
|
|
||||||
|
20. 有效的括号
|
||||||
|
简单
|
||||||
|
|
||||||
|
相关标签
|
||||||
|
相关企业
|
||||||
|
|
||||||
|
提示
|
||||||
|
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
|
||||||
|
|
||||||
|
有效字符串需满足:
|
||||||
|
|
||||||
|
左括号必须用相同类型的右括号闭合。
|
||||||
|
左括号必须以正确的顺序闭合。
|
||||||
|
每个右括号都有一个对应的相同类型的左括号。
|
||||||
|
|
||||||
|
示例 1:
|
||||||
|
|
||||||
|
输入:s = "()"
|
||||||
|
输出:true
|
||||||
|
示例 2:
|
||||||
|
|
||||||
|
输入:s = "()[]{}"
|
||||||
|
输出:true
|
||||||
|
示例 3:
|
||||||
|
|
||||||
|
输入:s = "(]"
|
||||||
|
输出:false
|
||||||
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {string} s
|
||||||
|
* @return {boolean}
|
||||||
|
*/
|
||||||
|
const isValid = function (s) {
|
||||||
|
const len = s.length;
|
||||||
|
const task = [s.charAt(0)];
|
||||||
|
for (let i = 1; i < len; i++) {
|
||||||
|
const pre = task.pop();
|
||||||
|
const cur = s.charAt(i);
|
||||||
|
const ss = pre + cur;
|
||||||
|
if (ss !== '()' && ss !== '[]' && ss !== '{}') {
|
||||||
|
if (pre) task.push(pre);
|
||||||
|
task.push(cur);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return task.length === 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log(isValid(''));
|
Loading…
x
Reference in New Issue
Block a user