Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()" Output: true
def valid(parentheses):
pairs_list = []
par = ["([{", ")]}"]
for i in parentheses:
if i in par[0]:
pairs_list.append(i)
elif i in par[1] and not len(pairs_list):
return False
elif i in par[1] and pairs_list[len(pairs_list) - 1] == par[0][par[1].index(i)]:
pairs_list.pop()
else:
pass
if len(pairs_list):
return False
else:
return True
if __name__ == "__main__":
parentheses = input("please input the parentheses")
print("valid is :", valid(parentheses))
more pythonic:
def valid(parentheses):
map = {')': '(', ']': '[', '}': '{'}
list = []
for e in parentheses:
if e in map and (list and list[-1] == map[e]):
list.pop()
else:
list.append(e)
#print(e)
return not list