16. Longest Valid Parentheses
Given a string containing just the characters '('
and ')'
, find the length of the longest valid (well-formed) parentheses substring.
Solution: (Using Stack)
Approach: For ever ‘(’ encountered, we push its index onto the stack. For every ')' encountered, we pop the topmost element and subtract the current element's index from the top element of the stack, which gives the length of the currently encountered valid string of parentheses.
Time Complexity: O(n) Space Complexity: O(n)
Last updated