class Solution(object):
"""
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"
输出: true
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
"""
@author : jiyanjiao
@date :2020-4-8
"""
# 基本解法
@staticmethod
def isValid(s):
"""
:type s: str
:rtype: bool
"""
for i in s:
if i == "(":
index_begin = s.find("(")
index_end = s.find(")")
if index_end == -1:
print("False")
return
index_r1 = s.find("[", index_begin, index_end)
index_r2 = s.find("{", index_begin, index_end)
index_r3 = s.find("]", index_begin, index_end)
index_r4 = s.find("}", index_begin, index_end)
if index_r1 == -1 and index_r2 == -1 and index_r3 == -1 and index_r4 == -1:
print("True")
else:
print("False")
elif i == "[":
index_begin = s.find("[")
index_end = s.find("]")
index_r1 = s.find("(", index_begin, index_end)
index_r2 = s.find("{", index_begin, index_end)
index_r3 = s.find(")", index_begin, index_end)
index_r4 = s.find("}", index_begin, index_end)
if index_r1 == -1 and index_r2 == -1 and index_r3 == -1 and index_r4 == -1:
print("True")
else:
print("False")
elif i == "{":
index_begin = s.find("{")
index_end = s.find("}")
index_r1 = s.find("(", index_begin, index_end)
index_r2 = s.find("[", index_begin, index_end)
index_r3 = s.find(")", index_begin, index_end)
index_r4 = s.find("]", index_begin, index_end)
if index_r1 == -1 and index_r2 == -1 and index_r3 == -1 and index_r4 == -1:
print("True")
else:
print("False")
# 其他作者解法
@staticmethod
def isValid1(s):
"""
:type s: str
:rtype: bool
"""
stack = [] # 设置一个列表,把该列表当做栈来使用即可。
dic = {')': '(', '}': '{', ']': '['} # 使用字典存储括号,并且右括号为key,左括号为value
for char in s:
if char in dic.values(): # 左括号就入栈
stack.append(char)
elif char in dic.keys(): # 有右括号的话就进行比较,
if stack == [] or dic[char] != stack.pop():
return False
else:
return False # 不再字典中的输入直接输出错误
return stack == [] # 如果栈最后是空的,那么则符合要求,输出true,如果不是,则输出false,使用一个条件表达式
if __name__ == '__main__':
s = Solution
ss = "(]"
s.isValid1(ss)