Was it helpful?

Question

Program to check whether different brackets are balanced and well-formed or not in Python

PythonServer Side ProgrammingProgramming

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
    • otherwise,
      • push c into stack
  • return true when stack is empty, otherwise false

Let us see the following implementation to get better understanding −

Example

 Live Demo

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
raja
Published on 06-Oct-2020 09:22:07
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top