Skip to content

Latest commit

 

History

History
58 lines (47 loc) · 1.6 KB

File metadata and controls

58 lines (47 loc) · 1.6 KB

Dynamic Programming

We'd like to use dp[i] to represent the length of the substring end at i that meets the longest valid parentheses.

We can check if valid only encountering ), so we will perform state transition as encountering ).

TODO: unfinished!!

Stack

TODO: unfinished!!

Brute Force

fun longestValidParentheses(s: String): Int {
    var maxLength = 0
    for (start in 0 until s.length) {
        for (end in start + 2 until s.length step 2) {
            val substring = s.substring(start, end)
            if (isValid(substring)) {
                maxLength = max(maxLength, substring.length)
            }
        }
    }
    return maxLength
}

private fun isValid(s: String): Boolean {
    val stack = Stack<Char>()
    for (c in s) {
        if (c == '(') {
            stack.push(c)
        } else {
            if (stack.isEmpty()) return false
            stack.pop()
        }
    }
    return stack.isEmpty()
}
  • Time Complexity: O(n^3).
  • Space Complexity: O(n) for stack.

Failed Cases

  • "()(()"
  • "()(()()"
  • "()()(()"
  • "()(()())"

Nice Explanation