题目:
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.
我的做法:
def isValid(self, s):
d = dict([('(', ')'),('[', ']'),('{','}')])
a = []
for i in s:
if a and a[-1] in d.keys() and d[a[-1]] == i:
a.pop()
else:
a.append(i)
if a:
return False
else:
return True
参考:
deq = deque()
pair = {'(': ')', '[': ']', '{': '}'}
for letter in s:
if letter == '(' or letter == '[' or letter == '{':
deq.append(letter)
else:
if len(deq) > 0 and letter == pair[deq[-1]]:
deq.pop()
else:
return False
return len(deq) == 0
知识点:
python用pop 和append实现堆栈
python---创建字典的方式
1、用{}创建字典 x = {"a":"1", "b":"2"}
2、用内置函数dict()
x = dict(a="1", b="2")
x = dict((("a", "1"), ("b", "2"))) //元祖内元祖,列表内列表,元祖内列表,列表内元祖都ok
--------------新手刷题,仅用于自身记录,如有错误,欢迎指出---------------