原题:https://leetcode-cn.com/problems/valid-parentheses/
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"
输出: true
再加两个测试数据
示例 6:
输入: "(("
输出: false
示例 7:
输入: "))"
输出: false
当出现 {、[、(时,数组的最后元素需要是与之对应的 }、]、)
用数组解答:
const isValid = (str) => {
if (!str || str.length % 2 !== 0) {
return false;
}
const arr = [];
for (let i = 0; i < str.length; i++) {
const currentChar = str[i];
if (
currentChar === '[' ||
currentChar === '{' ||
currentChar === '('
) {
arr.push(currentChar);
} else {
const beforeChar = arr.pop();
if (
!beforeChar ||
(beforeChar === '[' && currentChar !== ']') ||
(beforeChar === '(' && currentChar !== ')') ||
(beforeChar === '{' && currentChar !== '}')
) {
return false;
}
}
}
return arr.length === 0;
};
通过对象存储括号的映射信息
const isValid = (str) => {
if (!str || str.length % 2 !== 0) {
return false;
}
const len = str.length,
brackets = {
'[': ']',
'{': '}',
'(': ')',
},
arr = [];
for (let i = 0; i < str.length; i++) {
const currentChar = str[i];
if (brackets[currentChar]) {
arr.push(currentChar);
} else {
const beforeChar = arr.pop();
if (!beforeChar || brackets[beforeChar] !== currentChar) {
return false;
}
}
}
return arr.length === 0;
};
本文将持续更新
关注专题 前端便利店 https://www.jianshu.com/c/c3f77a86d9a5 ,帮您省时省力!
网友评论