Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4c77c7a

Browse files
author
zhangxing
committed
feat: 栈 - 删除最外层的括号
1 parent 72c0407 commit 4c77c7a

6 files changed

+58
-0
lines changed

‎栈 - 删除最外层的括号.js‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// https://leetcode.cn/problems/remove-outermost-parentheses/
2+
3+
// 有效括号字符串为空 ""、"(" + A + ")" 或 A + B ,其中 A 和 B 都是有效的括号字符串,+ 代表字符串的连接。
4+
5+
// 例如,"","()","(())()" 和 "(()(()))" 都是有效的括号字符串。
6+
// 如果有效字符串 s 非空,且不存在将其拆分为 s = A + B 的方法,我们称其为原语(primitive),其中 A 和 B 都是非空有效括号字符串。
7+
8+
// 给出一个非空有效字符串 s,考虑将其进行原语化分解,使得:s = P_1 + P_2 + ... + P_k,其中 P_i 是有效括号字符串原语。
9+
10+
// 对 s 进行原语化分解,删除分解中每个原语字符串的最外层括号,返回 s 。
11+
12+
//
13+
14+
// 示例 1:
15+
16+
// 输入:s = "(()())(())"
17+
// 输出:"()()()"
18+
// 解释:
19+
// 输入字符串为 "(()())(())",原语化分解得到 "(()())" + "(())",
20+
// 删除每个部分中的最外层括号后得到 "()()" + "()" = "()()()"。
21+
// 示例 2:
22+
23+
// 输入:s = "(()())(())(()(()))"
24+
// 输出:"()()()()(())"
25+
// 解释:
26+
// 输入字符串为 "(()())(())(()(()))",原语化分解得到 "(()())" + "(())" + "(()(()))",
27+
// 删除每个部分中的最外层括号后得到 "()()" + "()" + "()(())" = "()()()()(())"。
28+
// 示例 3:
29+
30+
// 输入:s = "()()"
31+
// 输出:""
32+
// 解释:
33+
// 输入字符串为 "()()",原语化分解得到 "()" + "()",
34+
// 删除每个部分中的最外层括号后得到 "" + "" = ""。
35+
36+
var removeOuterParentheses = function (s) {
37+
let stack = [];
38+
let result = '';
39+
40+
for (let i = 0; i < s.length; i++) {
41+
if (s[i] === '(') {
42+
stack.push(s[i]);
43+
}
44+
45+
if (s[i] === ')') {
46+
stack.pop();
47+
}
48+
49+
// 当栈为空时说明一个原语就结束了
50+
if (stack.length) {
51+
res += s[i];
52+
}
53+
}
54+
return result;
55+
};
56+
57+
console.log(removeOuterParentheses('(()())(())'));
58+
console.log(removeOuterParentheses('(()())(())(()(()))'));
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /