代码改变世界

[LeetCode] 20. Valid Parentheses_Easy tag: Stack

2018-08-25 00:55  Johnson_强生仔仔  阅读(222)  评论(0编辑  收藏  举报

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