zoukankan      html  css  js  c++  java
  • 2.Valid Parentheses (括号匹配)

    Level:

    ​  Easy

    题目描述:

    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.

    思路分析:

    ​  简单的括号匹配问题,用map保存三种括号的对应关系,同时设置一个栈,遍历字符串,如果遇到的是左括号,那么入栈,如果遇到的是右括号,判断栈顶的符号是不是其对应的左括号,如果是则栈顶弹出,如果不是则括号不匹配,遍历完字符串后判断栈是否为空,如果为空则括号匹配,如果不为空,则不匹配。

    代码:

    class Solution {
        public boolean isValid(String s) {
            HashMap<Character,Character>map=new HashMap<>();
            map.put('(',')');
            map.put('[',']');
            map.put('{','}');
            Stack<Character>stack=new Stack<>();
            for(int i=0;i<s.length();i++){
                if(stack.isEmpty()){
                    if(s.charAt(i)==')'||s.charAt(i)==']'||s.charAt(i)=='}')
                        return false;
                    else
                        stack.push(s.charAt(i));
                }else{
                    if(s.charAt(i)==map.get(stack.peek()))
                        stack.pop();
                    else if(s.charAt(i)=='('||s.charAt(i)=='['||s.charAt(i)=='{')
                        stack.push(s.charAt(i));
                    else
                        return false;
                        
                }
            }
            if(stack.isEmpty())
                return true;
            else
                return false;
        }
    }
    
  • 相关阅读:
    phpcms基础
    读取数据库有的设置选中状态
    用php 生成 excel 表格
    ajax验证用户名是否存在,手机号是不是匹配
    系统登陆简单的密码验证
    分页显视
    时间选择的三级连动 年,月,日
    session控制登入权限
    jQuery, js 验证两次输了密码的一相同
    正则表达式判断手机号是否11位数字
  • 原文地址:https://www.cnblogs.com/yjxyy/p/10688523.html
Copyright © 2011-2022 走看看