题1021、删除最外层的括号

一、题目1

在这里插入图片描述

二、思路

最外层括号里面的括号要留下来

三、代码

public class T1021 {

    public static void main(String[] args) {
        System.out.println( removeOuterParentheses("(()())(())" ) );                //"()()()"
        System.out.println( removeOuterParentheses( "(()())(())(()(()))" ) );       //"()()()()(())"
        System.out.println( removeOuterParentheses( "()()" ) );                     //""

    }

    public static String removeOuterParentheses(String S) {

        String result = "";
        int flg = 0;
        
        //同样是正确方法,写法不一样而已
/*        for ( int i = 0; i < S.length(); i++ ){
            if ( S.charAt(i) == '(' ){
                flg++;
                if ( flg > 1 )
                    result += S.charAt(i) + "";
            }else{
                if ( flg > 1 )
                    result += S.charAt(i) + "";
                flg--;
            }
        }*/

        //遍历字符串,根据flg标记的信息进行删除括号
        for ( char i : S.toCharArray() ){
            
            //判断当前的字符是'('还是‘)’并根据结果进行不同的处理
            if ( i == '(' ){
                flg++;          //‘(’的话对flg进行加一
                
                //判断flg的值是否大于一,大于一的话就讲值存在结果集中
                if ( flg > 1 )
                    result += i + "";
            }else{
                //判断flg的值是否大于一,大于一的话就讲值存在结果集中
                if ( flg > 1 )
                    result += i + "";
                flg--;          //‘)’的话对flg进行减一
            }
        }

        return result;
    }
}

  1. 来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/remove-outermost-parentheses
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ↩︎

发布了48 篇原创文章 · 获赞 1 · 访问量 868

猜你喜欢

转载自blog.csdn.net/weixin_45980031/article/details/104117650
今日推荐