算法:移除最外层的括号1021. Remove Outermost Parentheses
Posted 架构师易筋
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法:移除最外层的括号1021. Remove Outermost Parentheses相关的知识,希望对你有一定的参考价值。
1021. Remove Outermost Parentheses
A valid parentheses string is either empty “”, “(” + A + “)”, or A + B, where A and B are valid parentheses strings, and + represents string concatenation.
For example, “”, “()”, “(())()”, and “(()(()))” are all valid parentheses strings.
A valid parentheses string s is primitive if it is nonempty, and there does not exist a way to split it into s = A + B, with A and B nonempty valid parentheses strings.
Given a valid parentheses string s, consider its primitive decomposition: s = P1 + P2 + … + Pk, where Pi are primitive valid parentheses strings.
Return s after removing the outermost parentheses of every primitive string in the primitive decomposition of s.
Example 1:
Input: s = "(()())(())"
Output: "()()()"
Explanation:
The input string is "(()())(())", with primitive decomposition "(()())" + "(())".
After removing outer parentheses of each part, this is "()()" + "()" = "()()()".
Example 2:
Input: s = "(()())(())(()(()))"
Output: "()()()()(())"
Explanation:
The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))".
After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())".
Example 3:
Input: s = "()()"
Output: ""
Explanation:
The input string is "()()", with primitive decomposition "()" + "()".
After removing outer parentheses of each part, this is "" + "" = "".
Constraints:
1 <= s.length <= 105
s[i]
is either ‘(’ or ‘)’.- s is a valid parentheses string.
超级优雅的解法,不用stack
class Solution {
public String removeOuterParentheses(String s) {
StringBuilder sb = new StringBuilder();
int open = 0;
for (char c: s.toCharArray()) {
if (c == '(' && open++ > 0) sb.append(c);
if (c == ')' && open-- > 1) sb.append(c);
}
return sb.toString();
}
}
以上是关于算法:移除最外层的括号1021. Remove Outermost Parentheses的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode #1021. Remove Outermost Parentheses 删除最外层的括号
LeetCode.1021-删除最外面的括号(Remove Outermost Parentheses)