- Trending Categories
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 maximum number of balanced groups of parentheses in Python
Suppose we have a string s that contains balanced parentheses "(" and ")", we have to split them into the maximum number of balanced groups.
So, if the input is like "(()())()(())", then the output will be ['(()())', '()', '(())']
To solve this, we will follow these steps −
- temp := blank string
- groups := a new list
- count := 0
- for each character b in s, do
- if count is same as 0 and size of temp > 0, then
- insert temp at the end of groups
- temp := blank string
- temp := temp concatenate b
- if b is same as '(', then
- count := count + 1
- otherwise,
- count := count - 1
- if count is same as 0 and size of temp > 0, then
- insert temp at the end of groups
- return groups
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, s): temp = '' groups = [] count = 0 for b in s: if count == 0 and len(temp) > 0: groups.append(temp) temp = '' temp += b if b == '(': count += 1 else: count -= 1 groups.append(temp) return groups s = "(()())()(())" ob = Solution() print(ob.solve(s))
Input
"(()())()(())"
Output
['(()())', '()', '(())']
Advertisements