LeetCode-removeOuterParentheses

问题描述

概括一下就是去除由多层括号组成的字符串中最外层的括号。以下是原文描述:
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

解决办法

匹配括号是栈的非常经典的用法
基本的思路是:

  1. 遍历字符串的每个字符,
  2. 如果是,如果栈为空,则说明推入的(一定是最外层的一个数据,如果不为空,则输出此(
  3. 如果是),说明栈内一定有数据,从栈内取出一个字符串,如果取出字符串后,栈不为空,则说明不是最外层的括号,则输出);如果此时栈为空,则说明这对()是最外层的,则不输出。

代码

public class RemoveOuterParentheses {

    public String removeOuterParentheses(String S) {
        Stack<Character> stack = new Stack<>();
        StringBuffer str = new StringBuffer();

        char[] ss = S.toCharArray();
        for(char c: ss) {
            if ('(' == c) {
                if (!stack.empty()) {
                    str.append(c);
                }
                stack.push(c);
            }

            if (')' == c) {
                stack.pop();
                if (!stack.empty()) {
                    str.append(c);
                }
            }
        }
        return str.toString();
    }
}

如果小伙伴们有更好的解决办法,欢迎留言探讨。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值