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
        }
    }
    
  • 相关阅读:
    Mongodb副本集集群搭建
    Mongodb分片副本集集群搭建
    python-字符串格式化
    python -序列化
    python-装饰器
    Python-内置函数
    CPU性能测试
    python-生成随机字符
    python-布尔值
    python学习-day3
  • 原文地址:https://www.cnblogs.com/zhongju/p/14195443.html
Copyright © 2011-2022 走看看