[LeetCode] 20. Valid Parentheses_Easy tag: Stack

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 20. Valid Parentheses_Easy tag: Stack相关的知识,希望对你有一定的参考价值。

Given a string containing just the characters ‘(‘‘)‘‘{‘‘}‘‘[‘ and ‘]‘, determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

这个题目就用stack, 不能用count了, 因为{[}]是invalid, 但是count没法判断. 那么为了elegant, 建一个hash table, d = {‘]‘:‘[‘, ‘}‘:‘{‘, ‘)‘:‘(‘}, 如果在d里面, 就通过判断stack是否为空和stack.pop() 是否跟d[c] 相等, 

如果在d.values()里面, 就append进入stack. 

 

Code:  T: O(n)  S; O(n)

class Solution:
    def validParenthesis(self, s):
        stack, d = [], {]:[, }:{, ):(}
        for c in s:
            if c in d and (not stack or stack.pop() != d[c]):
                return False
            elif c in d.values():
                stack.append(c)
        return not stack

 

以上是关于[LeetCode] 20. Valid Parentheses_Easy tag: Stack的主要内容,如果未能解决你的问题,请参考以下文章

leetcode20. Valid Parentheses

[LeetCode]20. Valid Parentheses

[LeetCode]20 Valid Parentheses 有效的括号

LeetCode OJ 20Valid Parentheses

Leetcode 20. Valid Parentheses

LeetCode 20. Valid Parentheses