LeetCode:20 有效的括号

89 阅读1分钟

「这是我参与2022首次更文挑战的第21天,活动详情查看:2022首次更文挑战

题目

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

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。

示例 1:

输入:s = "()"
输出:true

示例 2:

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

示例 3:

输入:s = "(]"
输出:false

示例 4:

输入:s = "([)]"
输出:false

示例 5:

输入:s = "{[]}"
输出:true

提示:

  • 1 <= s.length <= 104
  • s 仅由括号 '()[]{}' 组成

解题

解题一:栈

思路

建立一个符号栈负责保存传入的符号,如果是左边的符号就存入,如果是右边的符号就判断在栈中是否存在,存在就删除

代码

class Solution {
    public static boolean isValid(String s) {
        //"]":报错
        if (s.length() % 2 != 0) {
            return false;
        }
        char[] chars = s.toCharArray();
        char[] temp = new char[chars.length];
        int tail = 0;
        for (int index = 0; index < chars.length; index++) {
            if (chars[index] == ('(') || chars[index] == ('{') || chars[index] == ('[')) {
                temp[tail] = chars[index];
                tail++;
            } else if (chars[index] == (')')) {
                if (tail == 0 || temp[(tail - 1)] != ('(')) {
                    return false;
                } else {
                    tail--;
                }
            } else if (chars[index] == ('}')) {
                if (tail == 0 || temp[(tail - 1)] != ('{')) {
                    return false;
                } else {
                    tail--;
                }
            } else if (chars[index] == (']')) {
                if (tail == 0 || temp[(tail - 1)] != ('[')) {
                    return false;
                } else {
                    tail--;
                }
            }
        }
        if (tail != 0) {
            return false;
        }
        return true;
    }
}

总结

  • 执行耗时:0 ms,击败了 100.00% 的 Java 用户
  • 内存消耗:36.2 MB,击败了 87.30% 的 Java 用户