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

栈应用:有效的括号(第一题)

时间:2019-04-14 18:15:20      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:ase   and   ret   var   ssi   imp   style   判断字符串   expr   

问题:

给定一个只包括 ‘(‘‘)‘‘{‘‘}‘‘[‘‘]‘ 的字符串,判断字符串是否有效。

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。

注意空字符串可被认为是有效字符串。

 

分析:

三种模式的括号可能会出现 ‘ { [ ( } ‘  这种情况 所以单纯的通过计数方法来匹配肯定不行

这里运用栈这种数据结构的特点:先进后出 FIFO

遇上左括号直接压栈,右括号直接出栈并匹配,接着上代码

 1 class Solution(object):
 2     def isValid(self, s):
 3         """
 4         :type s: str
 5         :rtype: bool
 6         """
 7 
 8         # The stack to keep track of opening brackets.
 9         stack = []
10 
11         # Hash map for keeping track of mappings. This keeps the code very clean.
12         # Also makes adding more types of parenthesis easier
13         mapping = {")": "(", "}": "{", "]": "["}
14 
15         # For every bracket in the expression.
16         for char in s:
17 
18             # If the character is an closing bracket
19             if char in mapping:
20 
21                 # Pop the topmost element from the stack, if it is non empty
22                 # Otherwise assign a dummy value of ‘#‘ to the top_element variable
23                 top_element = stack.pop() if stack else #
24 
25                 # The mapping for the opening bracket in our hash and the top
26                 # element of the stack don‘t match, return False
27                 if mapping[char] != top_element:
28                     return False
29             else:
30                 # We have an opening bracket, simply push it onto the stack.
31                 stack.append(char)
32 
33         # In the end, if the stack is empty, then we have a valid expression.
34         # The stack won‘t be empty for cases like ((()
35         return not stack

 

参考:https://leetcode-cn.com/articles/valid-parentheses/

 

栈应用:有效的括号(第一题)

标签:ase   and   ret   var   ssi   imp   style   判断字符串   expr   

原文地址:https://www.cnblogs.com/dmndxld/p/10705883.html

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