- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 balanced subsequence in Python
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 −
Example
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))
Input
"())(()("
Output
4
Advertisements