来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"
输出: true
解题思路:看到这个题目最直观的想法就是递归,将整个字符串划分为无数个括号对,从外面不断递归直到递归到最中心即此时括号的个数小于等于2,就可以判断是否有效,AC代码如下:
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ length = len(s) if length % 2 == 1: return False else: return cal(s) def cal(s): # 进行计算 length = len(s) if length == 0: return True if length % 2 == 1: return False if length == 2: if check(s[0], s[1]): return True else: return False if s[0] == '(': flag = findLocation('(', s, ')') if not flag: return False return cal(s[1:flag]) and cal(s[flag + 1:]) elif s[0] == '[': flag = findLocation('[', s, ']') if not flag: return False return cal(s[1:flag]) and cal(s[flag + 1:]) elif s[0] == '{': flag = findLocation('{', s, '}') if not flag: return False return cal(s[1:flag]) and cal(s[flag + 1:]) else: return False def findLocation(leftchar, s, rightchar): # 找到对应右边括号的位置 left = 0 for i in range(len(s)): if s[i] == leftchar: left += 1 if s[i] == rightchar: left -= 1 if left == 0: return i def check(a, b): # 对中心的括号进行检查 if a == '(' and b == ')': return True elif a == '{' and b == '}': return True elif a == '[' and b == ']': return True else: return False
后来看到了别人的思路,觉得这种直接求解的做法太笨重了,可以利用栈的特性去求解(学习编译原理的时候对代码进行检查的时候学过),AC代码如下:
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ left = ['[', '(', '{'] right = [']', ')', '}'] stack = [] for i in s: if i in left: # 左括号 stack.append(i) elif stack: # 弹出 temp = stack.pop() for j in range(3): if left[j] == temp: index = j if i == right[index]: continue else: return False else: # 字符串以右括号开始 return False return True if not stack else False