Loading

[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
    }
}
posted @ 2020-12-27 09:27  Zhongju.copy()  阅读(78)  评论(0编辑  收藏  举报