Leetcode——1021. 删除最外层的括号(Java)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
原先没有思路,可以看看leetcode上的提示
在这里插入图片描述

class Solution {
    public String removeOuterParentheses(String S) {
        StringBuilder res = new StringBuilder();
        //定义两个变量记录左括号数量与右括号数量
        int leftcount = 0, rightcount = 0;
        for(int i=0; i<S.length(); i++){
        	//取出字符串中的每一个字符
            char ch = S.charAt(i);
    		//当字符为左括号时,计数
    		//如果leftcount == rightcount+1不做处理
    		//否则,添加进res中
            if(ch == '('){
                leftcount ++;
                if(leftcount == rightcount+1) continue;
                else {
                    res.append(ch);
                }    
            }
            //当字符为右括号时,计数
    		//如果leftcount == rightcount不做处理
    		//否则,添加进res中
            if(ch == ')'){
                rightcount ++;
                if(leftcount == rightcount) continue; 
                else{
                    res.append(ch);
                } 
            }
        }
        return res.toString();
    }
}

发布了46 篇原创文章 · 获赞 3 · 访问量 7642

猜你喜欢

转载自blog.csdn.net/qq_43604667/article/details/90310915
今日推荐