首页 > 学院 > 开发设计 > 正文

[Leetcode] 20. Valid Parentheses

2019-11-08 02:01:14
字体:
来源:转载
供稿:网友

PRoblem:

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

Idea: Use the stack to solve this problem. For every incoming left mark, just push into the stack. Then, for every incoming right mark, just check the top item in the stack, if top item matches the incoming right mark, pop the top item, else return False. Finally, after going throuth all items in string, just check if the stack is empty or not, if it is empty(means all pairs are matched and popped) then return True, else return False.

Solution:

class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ l = list() for item in s: if item == '(' or item == '{' or item == '[' : l.append(item) elif item == ')': if len(l) == 0: return False elif l[len(l)-1] == '(': l.pop() else: return False elif item == '}': if len(l) == 0: return False elif l[len(l)-1] == '{': l.pop() else: return False elif item == ']': if len(l) == 0: return False elif l[len(l)-1] == '[': l.pop() else: return False if len(l) == 0: return True else: return False
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表