• 32. Longest Valid Parentheses


    Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

    Example 1:

    Input: "(()"
    Output: 2
    Explanation: The longest valid parentheses substring is "()"
    

    Example 2:

    Input: ")()())"
    Output: 4
    Explanation: The longest valid parentheses substring is "()()"
    class Solution {
    public int longestValidParentheses(String s) {
        int maxans = 0;
        Stack<Integer> stack = new Stack<>();
        stack.push(-1);
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                stack.push(i);
            } else {
                stack.pop();
                if (stack.empty()) {
                    stack.push(i);//如果当前为右括号且为空,重新设置起始点
                } else {
                    maxans = Math.max(maxans, i - stack.peek());
                }
            }
        }
        return maxans;
    }
    }

    Instead of finding every possible string and checking its validity, we can make use of stack while scanning the given string to check if the string scanned so far is valid, and also the length of the longest valid string. In order to do so, we start by pushing -11 onto the stack.

    For every  ext{‘(’}‘(’ encountered, we push its index onto the stack.

    For every  ext{‘)’}‘)’ encountered, we pop the topmost element and subtract the current element's index from the top element of the stack, which gives the length of the currently encountered valid string of parentheses. If while popping the element, the stack becomes empty, we push the current element's index onto the stack. In this way, we keep on calculating the lengths of the valid substrings, and return the length of the longest valid string at the end.

  • 相关阅读:
    css 基线与行高
    requests超时
    小记--------Ambari2.7.4集成Kylin3.0
    记一次--------HDP3.1 spark创建表hive读不到,hive创建表spark读不到
    记一次-------- sqoop同步mysql到hive 执行太慢
    记一次--------hive创建表comment中文乱码解决
    .Net Core学习之路-跳坑(一)
    NGINX、HAProxy和Traefik负载均衡能力对比
    idea 一键启动多个微服务项目
    vuedraggable自由拖拽
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11406881.html
Copyright © 2020-2023  润新知