leetcode32: (Java)最长有效括号 :给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度。


示例 1:

输入: "(()"
输出: 2
解释: 最长有效括号子串为 "()"

思路:加入辅助数组,左括号直接进栈,辅助数组对应编号置0,右括号进看前面是否有配对,有左括号配对,将前面的左括号出栈,将当前右和左括号在辅助数组中对应位置置1,最后看连续的1的最大数返回。


class Solution {
    public int longestValidParentheses(String s) {
        List<ele> list = new ArrayList<ele>();

        int max = 0;
        int now = 0;
        int size = s.length();
        int[] tmp = new int[size];//辅助数组
        int i = 0;//辅助数组下标
        for(char c : s.toCharArray()){
            if(c == '('){
                list.add(new ele(i,c));
                tmp[i] = 0;
                i++;
                continue;
            }
            if(c==')'){
                if(list.isEmpty()||list.get(list.size()-1).getSmp() != '(') {
                    now = 0;
                    tmp[i] = 0;
                    i++;
                    continue;
                }
                else{
                    ele e = list.get(list.size() - 1);
                    tmp[e.getIndex()] = 1;
                    tmp[i] = 1;
                    i++;
                    list.remove(list.size()-1) ;
                    
                }
            }

        }
        //return max;
        for(int x=0;x<tmp.length;x++){
            if(tmp[x] == 1){
                now += 1;
                max = max > now?max:now;
            }
            else{
                now = 0;
            }
        }
        return max;
    }
    public static class ele{ //辅助类
        public int index;
        public char smp;
        public ele(int index,char smp){
            this.index = index;
            this.smp = smp;
        }
        public int getIndex(){
            return this.index;
        }
        public char getSmp(){
            return this.smp;
        }
    }
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值