20. Valid Parentheses

https://leetcode.com/problems/valid-parentheses/

solution

  • 括号合理: 任一位置,左括号数量大于等于右括号数量;最后位置,左等于右

class Solution:
    def isValid(self, s: str) -> bool:
        anchor = {
            ")": "(",
            "]": "[",
            "}": "{"
        }

        stack = []
        for sub in s:
            if sub in ['(', '[', '{']:
                stack.append(sub)
            else:
                if not stack or anchor[sub] != stack.pop(-1):
                    return False
                else:
                    continue

        if not stack:
            return True
        else:
            return False

时间复杂度:O() 空间复杂度:O()

follow up-括号类

241. Different Ways to Add Parentheses

282. Expression Add Operators

301 Remove Invalid Parentheses

1249. Minimum Remove to Make Valid Parentheses

921. Minimum Add to Make Parentheses Valid

32. Longest Valid Parentheses

22 Generate Parentheses

636. Exclusive Time of Functions

multi thread版本

  • 改成一个hashmap of stacks, key=thread_id, value=stack of events and timestamps, reduce到同一个function

591. Tag Validator

678. Valid Parenthesis String

  • 错误方案, 想通过大小比较。相当于中间漏掉了每一个*的具体变换,有的case不通过

1541. Minimum Insertions to Balance a Parentheses String

Last updated