#20 Valid Parentheses

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

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

---

Solution1

class Solution:
    def isValid(self, s: str) -> bool:
        left = ["(","[","{"]
        right = [")","]","}"]
        order = []
        # how many (),[],{} are opened
        state = [0,0,0]
        
        if s.count(left[0]) != s.count(right[0]) or \
        s.count(left[1]) != s.count(right[1]) or \
        s.count(left[2]) != s.count(right[2]):
            return False
        if len(s) > 0 and s[0] in right:
            return False
        
        for each in s:
            if each in left:
                state[left.index(each)] += 1
                order.append(each)
            else:
                if state[right.index(each)] == 0:
                    return False
                else:
                    if left.index(order[-1]) != right.index(each):
                        return False
                    else:
                        state[right.index(each)] -= 1
                        order.pop()
        
        if state == [0,0,0]:
            return True
        else:
            return False

Solution2

class Solution:
    def isValid(self, s: str) -> bool:
        mapping = {"(": ")", "[": "]",  "{": "}"}
        open_par = ("(", "[", "{")
        stack = []
        for each in s:
            if each in open_par:
                stack.append(each)
            elif stack and each == mapping[stack[-1]]:
                    stack.pop()
            else:
                return False
        return stack == []
posted @ 2019-11-14 00:19  MrDoghead  阅读(95)  评论(0编辑  收藏  举报