[問題] leecode20. Valid Parentheses

看板Python作者時間5年前 (2020/03/16 00:38), 編輯推噓1(1013)
留言14則, 5人參與, 5年前最新討論串1/1
題目: 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

03/16 00:48, 5年前 , 1F
len("()") = 2
03/16 00:48, 1F

03/16 00:52, 5年前 , 2F
建議判斷list是不是空的改成 if list,這表示存在
03/16 00:52, 2F

03/16 01:05, 5年前 , 3F
問題在你的 or 那邊
03/16 01:05, 3F

03/16 01:06, 5年前 , 4F
if "(" or "{" or "[" == s[i]:
03/16 01:06, 4F

03/16 01:06, 5年前 , 5F
判斷的是 if "(", if "{" 和 if "[" == s[i]
03/16 01:06, 5F

03/16 01:06, 5年前 , 6F
前兩個永遠都是 true
03/16 01:06, 6F

03/16 01:07, 5年前 , 7F
你寫的其他條件根本不會走進去
03/16 01:07, 7F

03/16 12:30, 5年前 , 8F
這應該用堆疊做吧
03/16 12:30, 8F

03/16 12:31, 5年前 , 9F
左向括號push右向pop
03/16 12:31, 9F

03/16 12:34, 5年前 , 10F
Pop前確定是同對等的括號
03/16 12:34, 10F

03/16 12:39, 5年前 , 11F
原來已經用堆疊做了。My bad
03/16 12:39, 11F

03/16 23:50, 5年前 , 12F
H大已講 or的兩邊True會進if 你or的兩邊是什麼
03/16 23:50, 12F

03/16 23:51, 5年前 , 13F
可以改成s[i] in ['[','{','(']
03/16 23:51, 13F

03/18 17:43, 5年前 , 14F
謝謝H大 已解決
03/18 17:43, 14F
文章代碼(AID): #1URbdjWj (Python)
文章代碼(AID): #1URbdjWj (Python)