首页 > 其他 > 详细

[LeetCode] 20. Valid Parentheses_Easy tag: Stack

时间:2018-08-25 10:59:46      阅读:159      评论:0      收藏: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

 

[LeetCode] 20. Valid Parentheses_Easy tag: Stack

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!