- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Program to find length of longest valid parenthesis from given string in Python

Suppose we have a string s. This s consists of opening and closing parenthesis only. We have to find the length of the longest valid (well-formed) parentheses substring. 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 solve(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.solve("))(())())"))

## Input

"))(())())"

## Output

6

- Related Questions & Answers
- Valid Parenthesis String in C++
- Program to find length of longest Fibonacci subsequence from a given list in Python
- Program to find length of longest alternating subsequence from a given list in Python
- Program to find length of longest sublist with given condition in Python
- Program to find length of longest matrix path length in Python
- Program to find length of longest word that can be formed from given letters in python
- Program to find length of longest arithmetic subsequence of a given list in Python
- Program to find length of longest repeating substring in a string in Python
- Program to find length of longest possible stick in Python?
- Program to find length of longest balanced subsequence in Python
- Program to find length of longest anagram subsequence in Python
- Program to find length of longest consecutive sequence in Python
- Program to find length of longest distinct sublist in Python
- Program to find length of longest increasing subsequence in Python
- Program to find length of longest palindromic substring in Python

Advertisements