zoukankan      html  css  js  c++  java
  • Longest Valid Parentheses

    描述
    Given a string containing just the characters ’(’ and ’)’, find the length of the longest valid (wellformed)
    parentheses substring.
    For ”(()”, the longest valid parentheses substring is ”()”, which has length = 2.
    Another example is ”)()())”, where the longest valid parentheses substring is ”()()”, which has
    length = 4.

    分析:字符串配对的()有效序列最大长度。

      遇到左括号,将其对应位置压栈。

      主要是遇到右括号的处理:

        1、如果栈为空,栈中无可与此右括号配对的左括号(有也是之前判断过的);同时记录右括号的位置:有效起始点。

        2、否则,栈顶元素(左括号)出栈,与当前右括号配对。

          1)出栈后,栈为空的话,有效序列长度为当前右括号位置与左括号的位置距离。

          2)否则,栈中还有左括号,有效长度为栈中括号位置的下一位置到右括号的距离。

    public int longestValidParentheses(String s) {
            Stack<Integer> left = new Stack<Integer>();
            int _max = 0, last = -1;
    
            for(int i = 0;  i < s.length(); ++i){
                if(s.charAt(i) == '(') {
                    left.add(i);
                }
                else {
                    if(left.empty()) {
                        last = i;
                    }
                    else {
                        left.pop();
                        if(left.empty()){
                            _max = Math.max(_max, i - last);
                        }else{
                            _max = Math.max(_max, i - left.peek());
                        }
                    }
                }
            }
            return _max;
        }
  • 相关阅读:
    JS常用数值验证
    JS遍历对象的属性和值
    SpringBoot解决特殊符号 []报400问题
    postman工具的用法
    SpringBoot使用谷歌方式生成图片验证码
    hibernate配置多对多ORM映射关系
    hibernate配置一对多ORM映射关系
    Class文件结构
    垃圾收集器与内存分配策略
    hibernate持久化类和一级缓存
  • 原文地址:https://www.cnblogs.com/zywu/p/5497968.html
Copyright © 2011-2022 走看看