zoukankan      html  css  js  c++  java
  • Leetcode 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.

    二、题目分析:

    1.符合题意的形式还有:嵌套形式:{ [ ( ) ] } ,{ ( [] ) [ ] }

    2.本题的经典在使用了 栈 的数据结构,先进后出,内层括号首先匹配,外层再进行匹配。

    3.解题思路:

      遍历所有输入的全部括号,

        若是左括号,则压入栈中。

        若是右括号,则和栈顶元素进行匹配。匹配成功则,则弹出栈顶元素,否则返回false,程序结束。

    三、代码:

    public class Solution {
        
        public boolean isValid(String s) {
            Stack<Character> stack=new Stack<Character>();
            for(int i=0;i<s.length();i++){
                char c=s.charAt(i);
                if(c!='}' && c!=']' && c!=')'){
                    stack.push(c);
                }else{
                    if(stack.isEmpty())
                       return false; 
                    char topChar=stack.peek();
                    switch(c){
                        case ')':
                            if(topChar=='('){
                                stack.pop();
                            }else{
                                return false;
                            }
                            break;
                        case ']':
                            if(topChar=='['){
                                stack.pop();
                            }else{
                                return false;
                            }
                            break; 
                        case '}':
                            if(topChar=='{'){
                                stack.pop();
                            }else{
                                return false;
                            }
                            break;
                }
            }
        }
                if(stack.isEmpty()){
                     return true;
                }else{
                    return false;
                }
       
    }
    }        
  • 相关阅读:
    Hadoop
    java获取系统指定时间年月日
    JS获取系统的指定定年月日
    nodetree中 前面复选框禁用插件
    JS生成指定长度的随机数
    Post的请求案例
    Ajax的简单请求案例
    from 表单提交
    Oracle中添加视图
    java double保留小数点的零的问题,java保留小数点问题
  • 原文地址:https://www.cnblogs.com/lyr2015/p/6340361.html
Copyright © 2011-2022 走看看