[問題] leecode20. Valid Parentheses
題目:
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
03/16 00:48, 1F
推
03/16 00:52,
5年前
, 2F
03/16 00:52, 2F
→
03/16 01:05,
5年前
, 3F
03/16 01:05, 3F
→
03/16 01:06,
5年前
, 4F
03/16 01:06, 4F
→
03/16 01:06,
5年前
, 5F
03/16 01:06, 5F
→
03/16 01:06,
5年前
, 6F
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
03/16 12:31, 9F
→
03/16 12:34,
5年前
, 10F
03/16 12:34, 10F
→
03/16 12:39,
5年前
, 11F
03/16 12:39, 11F
→
03/16 23:50,
5年前
, 12F
03/16 23:50, 12F
→
03/16 23:51,
5年前
, 13F
03/16 23:51, 13F
→
03/18 17:43,
5年前
, 14F
03/18 17:43, 14F
Python 近期熱門文章
PTT數位生活區 即時熱門文章