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 <= 10000S[i]is"("or")"Sis a valid parentheses string
//Java
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();
}
}
//C++
class Solution {
public:
string removeOuterParentheses(string S) {
string res;
int opened = 0;
for (char c : S) {
if (c == '(' && opened++ > 0) res += c;
if (c == ')' && opened-- > 1) res += c;
}
return res;
}
};
博客围绕有效括号字符串展开,介绍了有效括号字符串及原始有效括号字符串的定义,给定一个有效括号字符串,需对其进行原始分解,最终要去除每个原始字符串的最外层括号并返回结果,还给出了示例。

被折叠的 条评论
为什么被折叠?



