zoukankan      html  css  js  c++  java
  • [leedcode 20] Valid Parentheses

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

    The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

    public class Solution {
        public boolean isValid(String s) {
            //题解:需要辅助栈进行判断,时间复杂度为O(n),空间复杂度为O(n)
            //遇到左括号则进栈,遇到右括号时需要判断:1.栈是否为空,2.栈顶是否和此符号匹配。二者有一个条件不匹配则返回false
            //注意以下几个细节:
            //1.出栈时需要判断栈空
            //2.最终返回结果需要判断栈是否为空
            Stack<Character> stack=new Stack<Character>();
            for(int i=0;i<s.length();i++){
                char temp=s.charAt(i);
                if(temp=='('||temp=='{'||temp=='[')
                     stack.push(temp);
                else{
                    if(temp==')'){
                        if(!stack.empty()&&(char)stack.peek()=='(')
                              stack.pop();
                        else 
                           return false;
                    }
                    if(temp==']'){
                        if(!stack.empty()&&(char)stack.peek()=='[')
                              stack.pop();
                        else 
                           return false;
                    }
                    if(temp=='}'){
                        if(!stack.empty()&&(char)stack.peek()=='{')
                              stack.pop();
                        else 
                           return false;
                    }
    
                }
    
            }
            return stack.empty();
        }
    }
  • 相关阅读:
    js函数动态传参
    js 异步加载
    js 遍历
    安卓——implements——OnClickListener
    安卓——BroadcastReceiver
    关于Linux下的硬链接
    Linux 的文件类型
    linux 学习
    虚函数与重载函数的区别
    虚函数和友元
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4627741.html
Copyright © 2011-2022 走看看