Uriel's Corner

Research Associate @ Harvard University / Research Interests: Computer Vision, Biomedical Image Analysis, Machine Learning
posts - 0, comments - 50, trackbacks - 0, articles - 594
判断由{[()]}组成的字符串是否合法(能匹配上),简单栈操作


 1 #20
 2 #Runtime: 18 ms (Beats 66.75%)
 3 #Memory: 13.7 MB (Beats 36.29%)
 4 
 5 class Solution(object):
 6     def isValid(self, s):
 7         """
 8         :type s: str
 9         :rtype: bool
10         """
11         par_stk = []
12         for i in s:
13             if i == ')' and len(par_stk) > 0 and par_stk[-1] == '(':
14                 par_stk.pop()
15                 continue
16             if i == '}' and len(par_stk) > 0 and par_stk[-1] == '{':
17                 par_stk.pop()
18                 continue
19             if i == ']' and len(par_stk) > 0 and par_stk[-1] == '[':
20                 par_stk.pop()
21                 continue
22             par_stk.append(i)
23         if par_stk:
24             return False
25         return True

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理