• Lc20-Valid Parentheses


    import java.util.Stack;
    
    /*
     * Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
    
    An input string is valid if:
    
    Open brackets must be closed by the same type of brackets.
    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
    
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/valid-parentheses
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
     */
    public class Lc20 {
        public static boolean isValid(String s) {
            Stack<Character> stack = new Stack<Character>();
            boolean isValid = false;
    
            char[] ch = s.toCharArray();
            for (char c : ch) {
                if ('(' == c) {
                    stack.push(c);
                } else if ('[' == c) {
                    stack.push(c);
                } else if ('{' == c) {
                    stack.push(c);
                } else if (!stack.isEmpty()) {
                    if (')' == c) {
                        Character temp = stack.pop();
                        if ('(' != temp) {
                            return false;
                        }
                    } else if (']' == c) {
                        Character temp = stack.pop();
                        if ('[' != temp) {
                            return false;
                        }
                    } else if ('}' == c) {
                        Character temp = stack.pop();
                        if ('{' != temp) {
                            return false;
                        }
                    }
                } else {
                    return false;
                }
    
            }
            if (stack.isEmpty()) {
                isValid = true;
            }
            return isValid;
        }
    
        public static void main(String[] args) {
            String s = "{";
            System.out.println(isValid(s));
        }
    
    }
  • 相关阅读:
    jquery类似方法的比较(二)
    获取数组中最大值的方法(最小值同理)
    jquery类似方法的比较(一)
    余老板
    N小时改变一次url时间戳的方法
    元素的前后关系
    损失函数, 成本函数, 目标函数的区别
    Ternsorflow 学习:005-MNIST入门 实现模型
    arm linux 移植支持 HP打印机
    在Anaconda3环境下安装并切换 Tensorflow 2.0 环境
  • 原文地址:https://www.cnblogs.com/xiaoshahai/p/12191059.html
Copyright © 2020-2023  润新知