zoukankan      html  css  js  c++  java
  • leetcode — valid-parentheses

    import java.util.Stack;
    
    /**
     * Source : https://oj.leetcode.com/problems/valid-parentheses/
     *
     * Created by lverpeng on 2017/7/11.
     *
     * * 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 ValiadParentheses {
    
        /**
         * 括弧匹配,使用栈进行判断,遇到左括号入栈,遇到右括号判断出栈,如果匹配则出栈,不匹配返回
         * 最后判断是否匹配完成,并判断栈是否为空
         *
         * @param str
         * @return
         */
        public boolean valiad (String str) {
            Stack<Character> stack = new Stack<Character>();
            for (int i = 0; i  < str.length(); i++) {
                char c = str.charAt(i);
                if (c == '(' || c == '[' || c == '{') {
                    stack.push(c);
                } else if (c == ')' || c == ']' || c == '}') {
                    char pop = stack.pop();
                    if (!((pop == '(' && c == ')') || (pop == '[' && c == ']') || (pop == '{' && c == '}'))) {
                        return false;
                    }
                } else {
                    return false;
                }
            }
            return stack.empty();
        }
    
    
        public static void main(String[] args) {
            ValiadParentheses valiadParentheses = new ValiadParentheses();
            System.out.println("true-------" + valiadParentheses.valiad("{}[]()"));
            System.out.println("true-------" + valiadParentheses.valiad("{[()]}[]()"));
            System.out.println("true-------" + valiadParentheses.valiad("{}[({})]()"));
            System.out.println("false-------" + valiadParentheses.valiad("{}[[()]"));
            System.out.println("false-------" + valiadParentheses.valiad("{}[][(]"));
            System.out.println("false-------" + valiadParentheses.valiad("{}2[][]()[]"));
    
        }
    
    
    }
    
  • 相关阅读:
    微信小程序传参 查询数据库,显示在小程序上
    jquery 的$.ajax() 与php后台交互
    Laravel 7 中文文档
    phpStudy配置
    Mysql 聚合函数 嵌套使用
    MySQL 的IFNULL()、ISNULL()和NULLIF()函数
    MySQL 定义变量,并且可以当value 值插入
    排序算法之冒泡排序
    排序算法之快速排序
    链表之反转链表
  • 原文地址:https://www.cnblogs.com/sunshine-2015/p/7368386.html
Copyright © 2011-2022 走看看