给定一个只包括 ‘(‘,’)’,’{‘,’}’,’[‘,’]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
示例1:
输入:s = “()” 输出:true
示例2:
输入:s = “()[]{}” 输出:true
示例3:
输入:s = “([)]” 输出:false
示例4:
输入:s = “{[]}” 输出:true
提示:
- 1 <= s.length <= 104
- s 仅由括号 ‘()[]{}’ 组成
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
枚举+栈
时间复杂度:O(n)
空间复杂度:O(n)
function isValid(s: string): boolean {const types = {'(': { type: 1, insert: true }, ')': { type: 1, insert: false }, '[': { type: 2, insert: true}, ']': { type: 2, insert: false }, '{': { type: 3, insert: true }, '}': { type: 3, insert: false }};const stack = [];for(let i = 0; i < s.length; i++) {const charType = types[s.charAt(i)];if (charType) {if(charType.insert) {stack.push(charType.type);} else {const lastCharType = stack.pop();if (charType.type !== lastCharType) {return false;}}}}return stack.length === 0;};
或者
function isValid(s: string): boolean {
const map = { '(': ')', '[': ']', '{': '}' }
const stack = [];
for(let i = 0; i < s.length; i++) {
const char = s.charAt(i);
if (char in map) {
stack.push(char);
} else if (Object.values(map).includes(char)) {
const lastChar = stack.pop();
if (char !== map[lastChar]) {
return false;
}
}
}
return stack.length === 0;
};
或者
function isValid(s: string): boolean {
const map = { '(': ')', '[': ']', '{': '}' }
const stack: Array<string> = [];
for(let i = 0; i < s.length; i++) {
const char = s.charAt(i);
stack.push(char);
if (stack.length < 2) continue;
const lastChar = stack[stack.length - 1];
const lastSecondChar = stack[stack.length - 2];
if (map[lastSecondChar] === lastChar) {
stack.pop();
stack.pop();
}
}
return stack.length === 0;
};
