20.有效的括号
给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"
输出: true
思想:使用栈
自己的代码:
#valid-parentheses
class Solution:
def isValid(self, s):
li = ['(',')','{','}','[',']']
dic = {'(':')','{':'}','[':']'}
res = ''
for i in s:
if i in li:
res += i
if len(res) % 2 != 0:
return False
stack = []
for i in res:
if i in dic:
stack.append(i)
else:
if stack == [] or dic[stack.pop()] != i:
return False
if stack != []:
return False
return True
if __name__ == '__main__':
print(Solution().isValid("(("))
执行时间:60 ms
PS:
其中还应该判断是否为空:
if len(res) % 2 != 0 or len(res) == 0
所以就改成了 :
f len(res) % 2 != 0
大神的写法:
class Solution(object):
def isValid(self, s):
d = {')': '(', ']': '[', '}': '{'}
stack = [None]
for i in s:
if i in d and d[i] == l[-1]:
stack.pop()
else:
stack.append(i)
return len(stack) == 1
执行时间:44 ms
time:O(n)
space:O(n)
链接:
https://leetcode-cn.com/problems/valid-parentheses/description/