Problem · String

Longest Valid Parentheses

Learn this problem
HardMathWorks logoMathWorksFULLTIMEONSITE INTERVIEW

Problem statement

Given a string s containing only ( and ), return the length of the longest contiguous substring that forms valid parentheses.

A parentheses string is valid when every opening parenthesis is matched with a later closing parenthesis and no prefix contains more closing parentheses than opening parentheses.

Function

longestValidParentheses(s: String) → int

Examples

Example 1

s = "(()"return = 2

The longest valid contiguous substring is (), with length 2.

Example 2

s = ")()())"return = 4

The longest valid contiguous substring is ()(), with length 4.

Example 3

s = ""return = 0

The empty string contains no non-empty valid substring.

Constraints

  • 0 <= s.length <= 3 * 10^4
  • s contains only ( and ).

More MathWorks problems

drafts saved locally
public int longestValidParentheses(String s) {
    // Write your code here.
}
s"(()"
expected2
checking account