zoukankan      html  css  js  c++  java
  • 20. Valid Parentheses (JAVA)

    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
    class Solution {
        public boolean isValid(String s) {
            Stack<Character> stack = new Stack<>(); //Primitive types such as char cannot be used as type parameters in Java. You need to use the wrapper type
    
            for(int i = 0; i < s.length(); i++){
                if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{'){
                    stack.push(s.charAt(i));
                }
                else if(s.charAt(i) == ')') {
                    if(stack.empty() || stack.peek() != '(') return false;
                    stack.pop();
                }
                else if(s.charAt(i) == ']'){
                    if(stack.empty() || stack.peek() != '[') return false;
                    stack.pop();
                }
                else if(s.charAt(i) == '}'){
                    if(stack.empty() || stack.peek() != '{') return false;
                    stack.pop();
                }
            }
            if(!stack.empty()) return false;
            return true;
        }
    }
  • 相关阅读:
    MySQL事务
    MySQL索引
    MySQL基础
    设计模式之单例模式
    设计模式之适配器模式
    zookeeper学习记录第二篇-----安装、配置、启动
    Scrapy 安装
    shiro
    python 爬虫简介以及使用方法
    linux VMware使用
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/10775310.html
Copyright © 2011-2022 走看看