This is a Leetcode problem -
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
Example 2 -
Input: "()[]{}" Output: True
Example 3 -
Input: "(]" Output: False
Example 4 -
Input: "([)]" Output: False
Example 5 -
Input: "{[]}" Output: True
Here is my solution to this challenge -
def is_valid(s):
if len(s) == 0:
return True
parentheses = ['()', '[]', '{}']
flag = False
while len(s) > 0:
i = 0
while i < 3:
if parentheses[i] in s:
s = s.replace(parentheses[i], '')
i = 0
flag = True
else:
i += 1
if len(s) == 0:
return True
else:
flag = False
break
return False
So I would like to know whether I could improve performance and make my code shorter.