- 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

Suppose we have a string s containing brackets parenthesis "(" and ")", we have to find the length of the longest subsequence of balanced brackets.

So, if the input is like s = "())(()(", then the output will be 4, as we can take the subsequence like "()()"

To solve this, we will follow these steps −

res := 0

n := size of s

close := 0

for i in range n - 1 to 0, decrease by 1, do

if s[i] is same as ")", then

close := close + 1

otherwise,

if close > 0, then

close := close - 1

res := res + 2

return res

Let us see the following implementation to get better understanding −

class Solution: def solve(self, s): res = 0 n = len(s) close = 0 for i in range(n - 1, -1, -1): if s[i] == ")": close += 1 else: if close > 0: close -= 1 res += 2 return res ob = Solution() s = "())(()(" print(ob.solve(s))

"())(()("

4

- Related Questions & Answers
- Program to find length of longest anagram subsequence in Python
- Program to find length of longest increasing subsequence in Python
- Program to find length of longest palindromic subsequence in Python
- Program to find length of longest fibonacci subsequence in Python
- Program to find length of longest circular increasing subsequence in python
- Program to find length of longest common subsequence in C++
- Program to find length of longest bitonic subsequence in C++
- Program to find length of longest common subsequence of three strings in Python
- Program to find out the length of longest palindromic subsequence using Python
- Program to find length of longest arithmetic subsequence with constant difference in Python
- Program to find length of longest arithmetic subsequence of a given list in Python
- 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 sign alternating subsequence from a list of numbers in Python
- Program to find length of longest matrix path length in Python

Advertisements