-
Notifications
You must be signed in to change notification settings - Fork 213
Expand file tree
/
Copy pathbalanced_brackets.py
More file actions
52 lines (39 loc) · 1014 Bytes
/
balanced_brackets.py
File metadata and controls
52 lines (39 loc) · 1014 Bytes
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
#import od module
import os
'''
SAMPLE INPUT =
3
{[()]}
{[(])}
{{[[(())]]}}
SAMPLE OUTPUT=
YES
NO
YES
'''
def isBalanced(s):
'''
Args:The string
s: String which is to be checked if it has all balanced brackets or no.
Returns: "YES" if the brackets are balanced in the string else it returns "NO".
'''
table = {')': '(', ']': '[', '}': '{'}
stack = []
for x in s:
if stack and table.get(x) == stack[-1]:
stack.pop()
else:
stack.append(x)
if stack:
return "NO"
else:
return "YES"
#main program
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input()) #takes the input ie number of test cases from user
for t_itr in range(t):
s = input() #string taken as input from the user
result = isBalanced(s) #isBalanced(s) function will return "YES" if the brackets are balanced else it will return "NO
fptr.write(result + '\n')
fptr.close()