题目大意

判断括号开闭

解题思路


简单题,思路正确即可

代码

class Solution(object):
    def isValid(self, s):
        """ :type s: str :rtype: bool """
        stack = []
        for char in s:
            if char == '(' or char == '{' or char == '[':
                stack.append(char)
                continue
            elif char == ')':
                temp = '('
            elif char == '}':
                temp = '{'
            elif char == ']':
                temp = '['
            else:
                return False

            if stack:
                if stack[-1] == temp:
                    stack.pop()
                else:
                    return False
            else:
                return False

        if len(stack) != 0:
            return False
        return True

由于pop()时会输出pop的数值,所以可以简化:

class Solution:
    # @return a boolean
    def isValid(self, s):
        stack = []
        for i in range(len(s)):
            if s[i] == '(' or s[i] == '[' or s[i] == '{':
                stack.append(s[i])
            if s[i] == ')':
                if stack == [] or stack.pop() != '(':
                    return False
            if s[i] == ']':
                if stack == [] or stack.pop() != '[':
                    return False
            if s[i] == '}':
                if stack == [] or stack.pop() != '{':
                    return False
        if stack:
            return False
        else:
            return True

总结