一 问题描述
Valid Parentheses
Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
An input string is valid if:
-
- Open brackets must be closed by the same type of brackets.
-
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
- Open brackets must be closed in the correct order.
Example 1:
input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: trueNote:
翻译:
从一组字符串中判断每一个括号是否是合法的相互包裹。
二 解法
1. 第一解法(个人)
思路:
总体来说,使用栈这种数据结构,配合数组的reduce方法遍历。
代码:
// 使用reduce方法辅助遍历
function isValid(s) {
let map = {
'(': ')',
'{': '}',
'[': ']'
};
let res = s.split('').reduce((acc, item) => {
if (acc === null)
return null;
if("([{".indexOf(item) > -1) {
acc.push(item);
} else {
if (map[acc.pop()] !== item) {
return null;
}
}
return acc;
}, []);
return Array.isArray(res) && res.length === 0;
}
结果:
76 / 76 test cases passed.
Status: Accepted
Runtime: 48 ms
Memory Usage: 34.4 MB
2. 第二解法(个人)
思路:
reduce方法固定会遍历所有元素,并且reduce加和的作用不是很需要。可以在匹配到第一个不合法包裹的情况就退出,Array.prototype.some()
方法完美符合需求。
代码:
function isValidBetter(s) {
let map = {
'(': ')',
'{': '}',
'[': ']'
};
let acc = [];
return !s.split('').some((item) => {
if("([{".indexOf(item) > -1) {
acc.push(item);
return false;
} else {
if (map[acc.pop()] !== item) {
return true;
}
return false;
}
}) ? acc.length === 0 : false;
}
结果:
76 / 76 test cases passed.
Status: Accepted
Runtime: 48 ms
Memory Usage: 34.5 MB
By DoubleJan
2019.8.22