通过 pop 方法获取最后一个元素后发生 Java 堆栈错误

发布于 2025-01-20 10:33:45 字数 1703 浏览 0 评论 0原文

我有以下有关

public static void main(String[] args) {
        System.out.println(isBalanced("{(([])[])[]}"));
}

public static String isBalanced(String s) {
    Stack<Character> stack = new Stack<>();
    stack.push(s.charAt(0));

    for (int i = 1; i < s.length(); i++) {
        Character c = s.charAt(i);
        Character cStack = stack.peek();


        if (cStack == '{' && c == '}' 
            || cStack == '[' && c == ']' 
            || cStack == '(' && c == ')') {
            stack.pop();
        } else {
            stack.push(c);
        }
    }

    if (stack.isEmpty())
        return "YES";
    return "NO";
}

尽管该代码似乎没有任何问题,但它会在Hackerrank页面上引发以下错误。我已经在本地IDE中测试了输入,因为它是{(([])[] []},但是我不确定我是否需要获取最后一个元素(也许是由于 stack.peek(); stack.pop(); 。

通过字符cstack = href =“ https://www.hackerrank.com/challenges/balanced-brackets/problem” rel =“ nofollow noreferrer”> hackerrank 页面,让我知道什么问题

? :

public static String isBalanced(String s) {
    Stack<Character> stack = new Stack<>();
    stack.push(s.charAt(0));

    for (int i = 1; i < s.length(); i++) {
        Character c = s.charAt(i);

        if (c == '{' || c == '[' || c == '(') {
            stack.push(c);
        } else if (stack != null) {
            Character cStack = stack.peek();
            if (cStack == '{' && c == '}'
                    || cStack == '[' && c == ']'
                    || cStack == '(' && c == ')') {
                stack.pop();
            }
        }
    }
    if (stack.isEmpty())
        return "YES";
    return "NO";
}

I have the following code for the solution of Hackerrank.

public static void main(String[] args) {
        System.out.println(isBalanced("{(([])[])[]}"));
}

public static String isBalanced(String s) {
    Stack<Character> stack = new Stack<>();
    stack.push(s.charAt(0));

    for (int i = 1; i < s.length(); i++) {
        Character c = s.charAt(i);
        Character cStack = stack.peek();


        if (cStack == '{' && c == '}' 
            || cStack == '[' && c == ']' 
            || cStack == '(' && c == ')') {
            stack.pop();
        } else {
            stack.push(c);
        }
    }

    if (stack.isEmpty())
        return "YES";
    return "NO";
}

Although the code seems to working without any problem, it throws the following error on the Hackerrank page. I already test the input in my local IDE as it is {(([])[])[]}, but I am not sure if I need to get the last element (it maybe due to getting it via Character cStack = stack.peek(); and then stack.pop();.

So, could you please have a look at and test this code on Hackerrank page and let me know what is wrong?

Update:

public static String isBalanced(String s) {
    Stack<Character> stack = new Stack<>();
    stack.push(s.charAt(0));

    for (int i = 1; i < s.length(); i++) {
        Character c = s.charAt(i);

        if (c == '{' || c == '[' || c == '(') {
            stack.push(c);
        } else if (stack != null) {
            Character cStack = stack.peek();
            if (cStack == '{' && c == '}'
                    || cStack == '[' && c == ']'
                    || cStack == '(' && c == ')') {
                stack.pop();
            }
        }
    }
    if (stack.isEmpty())
        return "YES";
    return "NO";
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

如梦 2025-01-27 10:33:45

在调用 stack.peek() 之前,您需要检查堆栈是否为空。在空堆栈上调用 pop()peek() 将引发错误。
如果当前字符是左括号,则甚至不需要检查堆栈顶部。如果是右括号,则先检查栈是否为空。如果是,则返回 false。否则比较顶部的字符并做出决定。

Before calling stack.peek(), you need to check if the stack is empty or not. Calling pop() or peek() on an empty stack will raise an error.
If the current character is an opening bracket, you don't even need to check the stack top. If it is a closing bracket, then check if the stack is empty or not first. If it is, return false. Otherwise compare the top character and make a decision.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文