一 問題描述
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