zoukankan      html  css  js  c++  java
  • [LC] 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

    Time: O(N)

    Method 1:
    class Solution:
        def isValid(self, s: str) -> bool:
            if s is None:
                return False
            pair = {')': '(', '}': '{', ']':'['}
            res = []
            for char in s:
                if char in pair.values():
                    res.append(char)
                elif char in pair.keys():
                    if res and res[-1] == pair.get(char):
                        res.pop()
                    else:
                        return False
                else:
                    return False
            return res == []


    class Solution {
        public boolean isValid(String s) {
            LinkedList<Character> stack = new LinkedList<>();
            for (char c: s.toCharArray()) {
                if (c == '(' || c == '[' || c == '{') {
                    stack.offerFirst(c);
                } else if (c == ']') {
                    if (stack.isEmpty() || stack.pollFirst() != '[') {
                        return false;
                    }
                } else if (c == ')') {
                    if (stack.isEmpty() || stack.pollFirst() != '(') {
                        return false;
                    }
                } else if (c == '}') {
                    if (stack.isEmpty() || stack.pollFirst() != '{') {
                        return false;
                    }
                }
            }
            return stack.isEmpty();
        }
    }


    Method 2:
    class Solution:
        def isValid(self, s: str) -> bool:
            if s is None:
                return False
            left = ['(', '{', '[']
            right = [')', '}', ']']
            res = []
            for char in s:
                if char in left:
                    res.append(char)
                elif char in right:
                    if len(res) != 0 and self.match(res[-1], char):
                        res.pop()
                    else:
                        return False
            return len(res) == 0
        
        def match(self, l, r):
            return l=='(' and r==')' or l=='{' and r=='}' or l=='[' and r==']'
  • 相关阅读:
    Windows系统CMD窗口下,MySQL建库、还原数据库命令操作示例
    Java JPA 报java.lang.IllegalArgumentException: Validation failed for query for method public abstract ...异常的一种原因和解决办法
    MySQL 5.7 执行SQL报错:1055
    Java8使用实现Runnable接口方式创建新线程的方法
    模板方法模式
    策略模式
    观察者模式
    装饰器模式
    原型模式
    单例模式
  • 原文地址:https://www.cnblogs.com/xuanlu/p/11646530.html
Copyright © 2011-2022 走看看