码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 20. Valid Parentheses_Easy tag: Stack

时间:2018-08-25 11:42:25      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:open   note   通过   lse   type   min   ack   end   app   

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

标签:open   note   通过   lse   type   min   ack   end   app   

原文地址:https://www.cnblogs.com/Johnsonxiong/p/9532619.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!