Advertisement
jinhuang1102

20. Valid Parentheses

Oct 20th, 2018
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.32 KB | None | 0 0
  1. class Solution:             #这道题用的是Stack这个数据结构的特点
  2.     def isValid(self, s):
  3.         """
  4.        :type s: str
  5.        :rtype: bool
  6.        """
  7.         if not s:
  8.             return True
  9.        
  10.         st = []
  11.        
  12.         for i in range(0, len(s)):
  13.             if s[i] == "(" or s[i] is "{" or s[i] is "[": #如果是左括号就推到stack里面
  14.                 st.append(s[i])
  15.             else:
  16.                 # 如果是右括号,就把stack尾部的值pop出来进行比较。如果是匹配的就continue (continue就是当前的loop不跑了,进行下一个loop)                           
  17.                 if not st:
  18.                     return False
  19.                
  20.                 temp = st.pop()
  21.                 if s[i] is ")" and temp is "(":
  22.                     continue
  23.                    
  24.                 elif s[i] is "}" and temp is "{":
  25.                     continue
  26.                    
  27.                 elif s[i] is "]" and temp is "[":
  28.                     continue
  29.                 # 如果不匹配直接返回FALSE
  30.                 else:
  31.                     return False
  32.         # 当所有s里面的都跑完了,还要检查一下stack还有没有剩余的“左括号”,如果有剩余就说明没有足够的“右括号”来匹配。返回False        
  33.         return True if not st else False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement