algorighm/leetcode/简单/有效的括号.js
2024-05-22 18:15:25 +08:00

53 lines
932 B
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
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(''));