zoukankan      html  css  js  c++  java
  • [LeetCode] 32. Longest Valid Parentheses(最长合法括号对)

    Description

    Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
    给定一只包含 '('')' 的字符串,返回其最长合法括号对的长度。

    Examples

    Example 1

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

    Example 2

    Input: s = ")()())"
    Output: 4
    Explanation: The longest valid parentheses substring is "()()".
    

    Example 3

    Input: s = ""
    Output: 0
    

    Constraints

    • s <= s.length <= 3e4
    • s[i] is '(' or ')'.

    Solution

    首先,利用栈把匹配的括号找出来,具体规则如下:

    1. 遇到左括号:将其下标入栈;

    2. 遇到右括号:如果栈顶下标对应的是左括号,则弹出栈顶元素,否则将其下标入栈。

    这样做完,栈内剩下的是没有匹配的括号的下标,两个下标间构成的子串为合法括号对,比较这些括号队的长度即可(如果栈是空的,说明整个字符串都符合要求)。代码如下:

    import kotlin.math.max
    
    class Solution {
        fun longestValidParentheses(s: String): Int {
            val stack = ArrayDeque<Int>()
            for (i in s.indices) {
                if (s[i] == '(') {
                    stack.push(i)
                } else {
                    if (stack.isNotEmpty() && s[stack.peek()] == '(') {
                        stack.pop()
                    } else {
                        stack.push(i)
                    }
                }
            }
            if (stack.isEmpty()) {
                return s.length
            }
            var result = 0
            var end = s.length
            var begin = 0
            while (stack.isNotEmpty()) {
                begin = stack.pop()
                result = max(result, end - begin - 1)
                end = begin
            }
            return result
        }
    }
    
  • 相关阅读:
    ADO 缓存更新
    DBNavigator中把insert变为append
    JQuery 选择器
    VS2013默认打开HTML文件没有设计视图
    windows 关机 重启 命令
    java如何计算两个日期之间相差多少天?
    java的list集合操作List<T>转化List<Long>
    ExcelUtil工具类
    oracle的START WITH CONNECT BY PRIOR用法
    oracle的with as用法
  • 原文地址:https://www.cnblogs.com/zhongju/p/14195443.html
Copyright © 2011-2022 走看看