20. 有效的括号

我的解法

我的解法不够直观, 而且写起来繁琐.

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack = []
        for ch in s:
          if ch=='(' or ch=='[' or ch=='{':
            stack.append(ch)
          elif ch == ')' and len(stack) > 0 and stack[-1] == '(':
            stack.pop()
          elif ch == ']' and len(stack) > 0 and stack[-1] == '[':
            stack.pop()
          elif ch == '}' and len(stack) > 0 and stack[-1] == '{':
            stack.pop()
          else:
            return False
        if len(stack) == 0:
          return True
        else:
          return False

高效算法

class Solution:
    def isValid(self, s):

        d = {'}': '{', ']': '[', ')': '('}

        stk = [' ']

        for c in s:

            c2 = d.get(c, '')
            if stk[-1] == c2:
                stk.pop()
            elif c2:
                return False
            else:
                stk.append(c)

        return len(stk) == 1

你可能感兴趣的:(20. 有效的括号)