-
Notifications
You must be signed in to change notification settings - Fork 16
/
app.js
43 lines (40 loc) · 906 Bytes
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* * 题目名称:删除最外层的括号
* * 题目地址:https://leetcode-cn.com/problems/remove-outermost-parentheses
*/
// * 思路:
/**
* @param {string} S
* @return {string}
*/
var removeOuterParentheses = function (S) {
const bracket = { '(': ')' }
const stack = []
let res = []
const result = []
for (let i = 0; i < S.length; i++) {
const val = S[i]
if (bracket[val]) { // 左括号
stack.push(val)
} else { // 右括号
stack.pop()
}
if (stack.length === 0) {
// 存在一组有效括号
res.push(val)
const cur = [...res]
cur.shift()
cur.pop()
result.push(cur)
res = []
continue
}
res.push(val)
}
return result.flat().join('')
};
// 测试用例
let test = "(()())(())"
console.time('执行用时');
console.log(removeOuterParentheses(test));
console.timeEnd('执行用时');