zoukankan      html  css  js  c++  java
  • 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));
        }
    
    }
  • 相关阅读:
    用sed删除文件中指定行
    传输文件到docker容器
    RAID技术全解图解-RAID0、RAID1、RAID5、RAID100
    Best PDF Document Viewers for Linux Systems
    nvidia docker install
    cuda apt install
    Ubuntu16_18建立返回桌面、显示桌面的快捷图标的特殊方法
    Linux Shell sort排序常用命令
    linux cut用法
    DispatcherServlet的作用
  • 原文地址:https://www.cnblogs.com/xiaoshahai/p/12191059.html
Copyright © 2011-2022 走看看