LeetCode in Kotlin

32. Longest Valid Parentheses

Hard

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

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:

Solution

class Solution {
    fun longestValidParentheses(s: String): Int {
        var max = 0
        var left = 0
        var right = 0
        val n = s.length
        var ch: Char
        for (i in 0 until n) {
            ch = s[i]
            if (ch == '(') {
                left++
            } else {
                right++
            }
            if (right > left) {
                left = 0
                right = 0
            }
            if (left == right) {
                max = Math.max(max, left + right)
            }
        }
        left = 0
        right = 0
        for (i in n - 1 downTo 0) {
            ch = s[i]
            if (ch == '(') {
                left++
            } else {
                right++
            }
            if (left > right) {
                left = 0
                right = 0
            }
            if (left == right) {
                max = Math.max(max, left + right)
            }
        }
        return max
    }
}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy