• 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));
        }
    
    }
  • 相关阅读:
    Hibernate 中 get()和load()的区别
    Socket网络编程
    经典
    jsp的九大内置对象及EL表达式的隐含对象
    TreeSet
    centos7.4安装npm
    centos7.4中安装docker
    centos7安装nginx
    centos中安装基础环境
    在docker中安装mysql
  • 原文地址:https://www.cnblogs.com/xiaoshahai/p/12191059.html
Copyright © 2020-2023  润新知