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;
        }
    }
  • 相关阅读:
    mybatis-插入数据库中文报错问题
    springmvc-异常处理
    springmvc-拦截器
    springmvc-上传文件
    springMVC-响应数据与结果视图
    MFC 中CString 格式16进制转int 十进制
    Excel 二维数组(数据块)旋转/翻转技巧
    SWD通讯
    IIC时序详解
    用EXCEL做快速傅立葉轉換_FFT in Excel
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/10775310.html
Copyright © 2011-2022 走看看