题目

给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:

输入: "()"
输出: true

示例 2:

输入: "()[]{}"
输出: true

示例 3:

输入: "(]"
输出: false

分析

本题不难,主要就是个配对的问题。首先将左括号压入栈进行临时存储,再去判断对应的右括号是否存在,如果不是成对出现则认为不是有效字符串,如果是则认为是有效字符串。

解答

 public static boolean isValid(String s) {
   
        if (StringUtils.isEmpty(s)) {
   
            return true;
        }
        Stack<Character> parenthesesStack = new Stack<>();
        for (Character c : s.toCharArray()) {
   
            if (c == '(' || c == '[' || c == '{') {
   
                parenthesesStack.push(c);
            }
            if (c == ')') {
   
                if (parenthesesStack.isEmpty() || parenthesesStack.pop() != '(') {
   
                    return false;
                }
            }
            if (c == ']') {
   
                if (parenthesesStack.isEmpty() || parenthesesStack.pop() != '[') {
   
                    return false;
                }
            }
            if (c == '}') {
   
                if (parenthesesStack.isEmpty() || parenthesesStack.pop() != '{') {
   
                    return false;
                }
            }
        }

        return parenthesesStack.isEmpty();

    }