-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack2.py
45 lines (30 loc) · 1.1 KB
/
stack2.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
"""
Check for balanced paranthesis
Given a string s representing an expression containing various types of brackets: {}, (), and [], the task is to determine whether the brackets in the expression are balanced or not. A balanced expression is one where every opening bracket has a corresponding closing bracket in the correct order.
Example:
Input: s = “[{()}]”
Output: true
Explanation: All the brackets are well-formed.
Input: s = “[()()]{}”
Output: true
Explanation: All the brackets are well-formed.
Input: s = “([]”
Output: false
Explanation: The expression is not balanced as there is a missing ‘)’ at the end.
Input: s = “([{]})”
Output: false
Explanation: The expression is not balanced because there is a closing ‘]’ before the closing ‘}’.
"""
def solution(s):
stack = []
mapp = {')':'(',']':'[','}':'{'}
for char in s:
if char in mapp:
top = stack.pop() if stack else '#'
if mapp[char] != top:
return False
else:
stack.append(char)
return True
string=input()
print(solution(string))