关注 每天一道编程题 专栏,一起学习进步。
题目
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 = P_1 + P_2 + … + P_k, where P_i 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: “(()())(())”
Output: “()()()”
Explanation:
The input string is “(()())(())”, with primitive decomposition “(()())” + “(())”.
After removing outer parentheses of each part, this is “()()” + “()” = “()()()”.
Example 2:
Input: “(()())(())(()(()))”
Output: “()()()()(())”
Explanation:
The input string is “(()())(())(()(()))”, with primitive decomposition “(()())” + “(())” + “(()(()))”.
After removing outer parentheses of each part, this is “()()” + “()” + “()(())” = “()()()()(())”.
Example 3:
Input: “()()”
Output: “”
Explanation:
The input string is “()()”, with primitive decomposition “()” + “()”.
After removing outer parentheses of each part, this is “” + “” = “”.
Note:
S.length <= 10000
S[i] is "(" or ")"
S is a valid parentheses string
分析
字符串S只包含左括号和右括号,左括号和右括号匹配成一对,这就是一个“原始对 primitive”。
如果字符串Si不能拆成A+B的形式(A和B都是匹配好的括号对),则Si是原始对。
比如:Input: “(()())(())(()(()))”
按括号匹配拆成(()())、(())、(()(()))
这三个不是原始对,继续拆
(()()) --> ()()
(()) --> ()
(()(())) -->()(())
就是去掉外层括号
思路:
找出一个最典型的符合单位
(()) --> ()
对于一个基本单位,去掉第一个’(’,去掉最后一个’)’
初始化标记flag=0;
遍历字符串,
如果当前字符为’(‘且flag++>0,则加入到结果集(说明当前字符不是第一个’(’);
如果当前字符为’)‘且flag–>1,则加入到结果集(说明当前字符不是最后一个’)’);
用(()) --> ()演绎一下;
读入字符 | flag | flag++>0 或 flag–>1 是否成立 | 运算后flag值 | 结果集 |
---|---|---|---|---|
( | 0 | 0>0不成立 | 1 | 不操作 |
( | 1 | 1>0成立 | 2 | ( |
) | 2 | 2>1成立 | 1 | () |
) | 1 | 1>1不成立 | 0 | 不操作 |
解答
class Solution {
public String removeOuterParentheses(String S) {
StringBuilder s = new StringBuilder();
int opened = 0;
for (char c : S.toCharArray()) {
if (c == '(' && opened++ > 0) s.append(c);
if (c == ')' && opened-- > 1) s.append(c);
}
return s.toString();
}
}
凡是“配对”的题目,都可以考虑利用一个数加减进行匹配操作。