20. Valid Parentheses

https://leetcode.com/problems/valid-parentheses/arrow-up-right

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 Parenthesesarrow-up-right

282. Expression Add Operatorsarrow-up-right

301 Remove Invalid Parentheses

1249. Minimum Remove to Make Valid Parentheses

921. Minimum Add to Make Parentheses Validarrow-up-right

32. Longest Valid Parentheses

22 Generate Parentheses

636. Exclusive Time of Functionsarrow-up-right

multi thread版本

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

591. Tag Validatorarrow-up-right

678. Valid Parenthesis Stringarrow-up-right

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

1541. Minimum Insertions to Balance a Parentheses Stringarrow-up-right

Last updated