首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >16 Remove Outermost Parentheses

16 Remove Outermost Parentheses

作者头像
devi
发布2021-08-18 16:00:31
发布2021-08-18 16:00:31
5480
举报
文章被收录于专栏:搬砖记录搬砖记录

题目

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:

代码语言:javascript
复制
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

不操作

解答

代码语言:javascript
复制
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();
    }
}

凡是“配对”的题目,都可以考虑利用一个数加减进行匹配操作。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/02/05 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 分析
  • 解答
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档