423. Valid Parentheses
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.
Example
Example 1:
Input: "([)]" Output: False
Example 2:
Input: "()[]{}" Output: True
Challenge
Use O(n) time, n is the number of parentheses.
class Solution: """ @param s: A string @return: whether the string is a valid parentheses """ def isValidParentheses(self, s): # write your code here valarr = [] for each in s: print(valarr) if each == '{': valarr.append('{') if each == '(': valarr.append('(') if each == '[': valarr.append('[') if each == '}': if len(valarr) == 0 or valarr.pop() != '{': return False if each == ')': if len(valarr) == 0 or valarr.pop() != '(': return False if each == ']': if len(valarr) == 0 or valarr.pop() != '[': return False if len(valarr) == 0: return True else: return False
请登录之后再进行评论