Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 check whether different brackets are balanced and well-formed or not in Python
Suppose we have a string of brackets (round, curly, and square), we have to check whether the brackets are balanced (well-formed) or not.
So, if the input is like s = "([()()]{[]})()", then the output will be True
To solve this, we will follow these steps −
- stack := a new list
- d := a hash map with key-value pairs ('}', '{'),(')','('), (']', '[')
- for each character c in s, do
- if c is any one of '}])', then
- if stack is empty or top of stack is not same as d[c], then
- return False
- pop from stack
- if stack is empty or top of stack is not same as d[c], then
- otherwise,
- push c into stack
- if c is any one of '}])', then
- return true when stack is empty, otherwise false
Let us see the following implementation to get better understanding −
Example
class Solution:
def solve(self, s):
stack = []
d = {'}': '{',')': '(',']': '['}
for c in s:
if c in '}])':
if not stack or stack[-1] != d[c]:
return False
stack.pop()
else:
stack.append(c)
return not stack
ob = Solution()
print(ob.solve("([()()]{[]})()"))
Input
"([()()]{[]})()"
Output
True
Advertisements