作者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://www.ptt.cc/bbs/Python/M.1584290285.A.82D.html
→ Hsins: len("()") = 2 03/16 00:48
推 TitanEric: 建議判斷list是不是空的改成 if list,這表示存在 03/16 00:52
→ Hsins: 問題在你的 or 那邊 03/16 01:05
→ Hsins: if "(" or "{" or "[" == s[i]: 03/16 01:06
→ Hsins: 判斷的是 if "(", if "{" 和 if "[" == s[i] 03/16 01:06
→ Hsins: 前兩個永遠都是 true 03/16 01:06
→ Hsins: 你寫的其他條件根本不會走進去 03/16 01:07
→ alvinlin: 這應該用堆疊做吧 03/16 12:30
→ alvinlin: 左向括號push右向pop 03/16 12:31
→ alvinlin: Pop前確定是同對等的括號 03/16 12:34
→ alvinlin: 原來已經用堆疊做了。My bad 03/16 12:39
→ lericee: H大已講 or的兩邊True會進if 你or的兩邊是什麼 03/16 23:50
→ lericee: 可以改成s[i] in ['[','{','('] 03/16 23:51
→ Kuba4ma: 謝謝H大 已解決 03/18 17:43