有效的括号

注意边界条件

有效的括号_第1张图片

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        if len(s) == 0:
            return True

        i = 0
        while i < len(s):
            if (s[i] == ')' or s[i] == ']' or s[i] == '}') and stack:
                if s[i] == ')':
                    if stack[-1] != '(':
                        return False
                    else:
                        stack.pop()

                if s[i] == ']':
                    if stack[-1] != '[':
                        return False
                    else:
                        stack.pop()
                
                if s[i] == '}':
                    if stack[-1] != '{':
                        return False
                    else:
                        stack.pop()
            else:
                stack.append(s[i])

            i = i + 1

            if not stack and i == len(s):
                return True

        return False

你可能感兴趣的:(算法刷题笔记)