Home > OS >  Java Stack error after getting last element via pop method
Java Stack error after getting last element via pop method

Time:04-10

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";
}

CodePudding user response:

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.

  • Related