20.有效的括号
小于 1 分钟
20.有效的括号
/*
* @lc app=leetcode.cn id=20 lang=typescript
*
* [20] 有效的括号
*/
// @lc code=start
interface mapKey {
[key: string]: string;
}
function isValid(s: string): boolean {
const stack: string[] = [];
const map: mapKey = {
"(": ")",
"[": "]",
"{": "}"
};
for (let i = 0; i < s.length; i++) {
const char = s[i];
if (["(", "[", "{"].includes(char)) {
stack.push(char);
} else {
const top = stack.pop() || ""; // 取出数组中最后一项
if (char != map[top]) {
return false;
}
}
}
return stack.length === 0;
}
console.log(isValid('([)]'));
// @lc code=end
Loading...
