20. Valid Parentheses

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

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. 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

方法1:

class Solution:
    def isValid(self, s: str) -> bool:
        
        if len(s) == 0:
            return True
        
        brackets = {'(':')', '[':']', '{':'}', ')':'(', ']':'[', '}':'{'}
        duilie = []
        s_len = len(s)
        i = 0
        while i < s_len:
            if duilie:
                if duilie[-1] == brackets[s[i]]:
                    duilie.pop()
                else:
                    duilie.append(s[i])
            else:
                duilie.append(s[i])
            i += 1
                    
                    
        if len(duilie) == 0:
            return True
        else:
            return False
            

方法2:

class Solution:
    def isValid(self, s: str) -> bool:
        
        stack = []
        match = {'(':')', '[':']', '{':'}'}
        
        for c in s:
            if c in match:
                stack.append(c)
            else:
                if not stack or match[stack.pop()] != c:
                    return False
        
        return not stack

 

你可能感兴趣的:(面试题)