leetcode 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 = 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:

  1. S.length <= 10000
  2. S[i] is "(" or ")"
  3. S is a valid parentheses string

题目大意:

一个有效的括号字符串包括空串,"(" + A + ")", A + B, 其中A,B是有效的括号字符串,"+"代表字符串连接。

如果一个字符串S非空,并且不存在一种将其划分成A + B (A, B是非空的有效括号字符串)的方式,那么称S是原始的。

给定一个字符串,假设的原始分解为$S = P_1 + P_2 + ... + P_k$, 其中$P_i$是原始有效括号字符串。

返回去除S中每一个原始字符串最外层括号后的字符串。

 

思路:一个有效的原始括号字符串,表明左括号和右括号个数相同,既然我们只想去掉最外层的括号,只要发现它是第一个左括号,就不要,是最后一个右括号也不要。

用一个counter变量记录当前原始有效字符串左括号的个数。

 1 class Solution {
 2 public:
 3     string removeOuterParentheses(string S) {
 4         string ans;
 5         int counter = 0;
 6         for (int i = 0; i < S.length(); ++i) {
 7             if (counter != 0 && !(counter == 1 && S[i] == ')')) ans += S[i];
 8             if (S[i] == '(') 
 9                 counter++;
10             else
11                 counter--;
12         }
13         
14         return ans;
15     }
16 };

python3:

 1 class Solution:
 2     def removeOuterParentheses(self, S: str) -> str:
 3         res, counter = [], 0
 4         for c in S:
 5             if (counter != 0) and (not(counter == 1 and c == ')')): 
 6                 res.append(c)
 7             if c == '(': 
 8                 counter += 1
 9             else : 
10                 counter -= 1
11         return "".join(res)

 

posted @ 2019-12-31 13:41  琴影  阅读(215)  评论(0编辑  收藏  举报