作者Kuba4ma ()
看板Python
标题[问题] leecode20. Valid Parentheses
时间Mon Mar 16 00:38:03 2020
题目:
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.
code:
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack=list()
length=len(s)
if length%2!=0:
return False
else:
for i in range(length):
if "(" or "{" or "[" == s[i]:
stack.append(s[i])
elif ")" == s[i]:
if stack.pop() != "(":
return False
elif "}" == s[i]:
if stack.pop() != "{":
return False
elif "]" == s[i]:
if stack.pop() != "[":
return False
if len(stack)!=0:
return False
else:
return True
input是"()"会跑出False
不知道哪里出了问题
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 101.12.46.156 (台湾)
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1584290285.A.82D.html
1F:→ Hsins: len("()") = 2 03/16 00:48
2F:推 TitanEric: 建议判断list是不是空的改成 if list,这表示存在 03/16 00:52
3F:→ Hsins: 问题在你的 or 那边 03/16 01:05
4F:→ Hsins: if "(" or "{" or "[" == s[i]: 03/16 01:06
5F:→ Hsins: 判断的是 if "(", if "{" 和 if "[" == s[i] 03/16 01:06
6F:→ Hsins: 前两个永远都是 true 03/16 01:06
7F:→ Hsins: 你写的其他条件根本不会走进去 03/16 01:07
8F:→ alvinlin: 这应该用堆叠做吧 03/16 12:30
9F:→ alvinlin: 左向括号push右向pop 03/16 12:31
10F:→ alvinlin: Pop前确定是同对等的括号 03/16 12:34
11F:→ alvinlin: 原来已经用堆叠做了。My bad 03/16 12:39
12F:→ lericee: H大已讲 or的两边True会进if 你or的两边是什麽 03/16 23:50
13F:→ lericee: 可以改成s[i] in ['[','{','('] 03/16 23:51
14F:→ Kuba4ma: 谢谢H大 已解决 03/18 17:43