
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Longest Valid Parentheses in Python
Suppose we have a string, with opening and closing parentheses. We have to find the longest length of the valid (well-formed) parentheses. So if the input is like “))(())())”, then the result will be 6, as the valid string is “(())()”.
To solve this, we will follow these steps −
Make a stack, and insert -1., set ans := 0
for i in range 0 to length of stack – 1
if s[i] is opening parentheses, then insert i into stack
otherwise
if stack is not empty and top of stack is not -1 and s[stack top] is opening parentheses, then
top element from stack
ans := max of ans and i – stack top
otherwise insert i into stack
return ans
Example
Let us see the following implementation to get a better understanding −
class Solution(object): def longestValidParentheses(self, s): stack = [-1] ans = 0 for i in range(len(s)): if s[i] == "(": stack.append(i) else: if stack and stack[-1]!=-1 and s[stack[-1]] == "(": stack.pop() ans = max(ans,i - stack[-1]) else: stack.append(i) return ans ob = Solution() print(ob.longestValidParentheses("))(())())"))
Input
"))(())())"
Output
6
- Related Articles
- Finding the longest valid parentheses JavaScript
- Valid Parentheses in C++
- Minimum Add to Make Parentheses Valid in Python
- Maximum Nesting Depth of Two Valid Parentheses Strings in Python
- Program to find minimum remove required to make valid parentheses in Python
- Minimum Remove to Make Valid Parentheses in C++
- Program to find length of longest valid parenthesis from given string in Python
- Generate Parentheses in Python
- Minimum number of Parentheses to be added to make it valid in C++
- Check for balanced parentheses in Python
- Special Syntax with Parentheses in Python
- Valid Sudoku in Python
- Valid Palindrome in Python
- Valid Anagram in Python
- Valid Number in Python

Advertisements