Given an expression string, write a python program to find whether a given string has balanced parentheses or not.
Examples:
Input : {[]{()}}
Output : Balanced
Input : [{}{}(]
Output : Unbalanced
使用stack
- Each time, when an open parentheses is encontered push it in the stack, when closed parenthesis is encountered, match it withe top of stack and pop it. If stack is empty at the end, return Balanced otherwise, Unbalanced
open_list = ["[","{","("]
close_list = ["]","}",")"]
# Function to check parentheses
def check(myStr):
stack=[]
for i in myStr:
if i in open_list:
stack.append(i)
elif i in close_list:
pos=close_list.index(i)
if (len(stack)>0) and (stack[len(stack)-1]==open_list[pos]):
stack.pop()
else:
return "unbalanced"
if len(stack)==0:
return "balanced"
else:
return "unbalanced"
def main5():
string = "{[]{()}}"
print(string, "-", check(string))
string = "[{}{})(]"
print(string, "-", check(string))
main5()