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;
        }
  • 相关阅读:
    shell脚本判断语句和循环语句
    shell脚本基础
    Linux防火墙(Firewalls)
    RAID磁盘阵列
    LVM逻辑卷创建管理
    vue与django结合使用
    Python使用pyecharts绘制cpu使用量折线图
    Centos8 网络配置静态IP
    Html表格处理
    django的教程相关
  • 原文地址:https://www.cnblogs.com/zywu/p/5497968.html
Copyright © 2011-2022 走看看