forked from Algo-Phantoms/Algo-Tree
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Balanced_brackets.py
79 lines (65 loc) · 1.96 KB
/
Balanced_brackets.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# In this problem we are given a string expression
# with string elements as "{","}","[","]","(" and ")".
# We have to tell whether the brackets are balanced or not.
# For Ex:
# {([])} ----> this expression has balanced brackets.
# {][]) -----> this sequence does not have balanced brackets.
# In this problem we are given a string expression
# with string elements as "{","}","[","]","(" and ")".
# We have to tell whether the brackets are balanced or not.
# For Ex:
# {([])} ----> this expression has balanced brackets.
# {][]) -----> this sequence does not have balanced brackets.
s=input("Enter the expression\n")
#this stack will contain all the opening brackets
stack=[]
#this flag will tell if the brackets are balanced or not
flag=0
for i in s:
if((i == "(") or (i == "[") or (i == "{")):
stack.append(i)
else:
#if stack is empty brackets are
#not balanced
if not stack:
flag=1
break
#e will contain the last opening bracket
e=stack.pop()
#if opening and closing brackets are not same
#the brackets are not balanced
if(e == '{' and i != "}"):
flag=1
break
if(e == '(' and i != ")"):
flag=1
break
if(e == '[' and i != "]"):
flag=1
break
#if stack is not empty after
#transversing whole loop then
#brackets are not balanced
if(flag==0):
if stack:
flag=1
if(flag==1):
print("Brackets are not balanced")
else:
print("Brackets are balanced")
# TEST CASES
# 1)Input:
# Enter the expression
# {([])}
# Output:
# Brackets are balanced
#
#
# 2)Input:
# Enter the expression
# {([]
# Output:
# Brackets are not balanced
# Time complexity: O(n)
# Space complexity: O(n) , Here n is the length of the expression
#