Seek Addo Seek Addo - 5 months ago 7
Java Question

Why do i keep getting "false" for a bad bracketed expression in my Queue method?

Hey guys i am trying to use Queue to check for a good bracket and a bad bracket but i am having some problems with the bad brackets.
example:

1.. good bracketed expression
"a*[a+12]",
"a+(b)-c",
"a+{b+8+(b+c)}/a"

2..Bad bracketed expressions
"[", "(}",
"a)[]",
"([)]"--> i keep getting true for this instead of false.
"]["


Here is the code && thanks for the support:

private static boolean check(String string){
Queue<Character> chars = new LinkedList<>();
for (Character charr: string.toCharArray()){
if (charr.equals('{') || charr.equals('[') || charr.equals('(')){
chars.add(charr);
}else if (charr.equals('}')){
return (chars.contains('{') && chars.poll().equals('{'));
}else if (charr.equals(')')){
return (chars.contains('(') && chars.poll().equals('('));
}else if (charr.equals(']')){
return (chars.contains('[') && chars.poll().equals('['));
}
}
return chars.isEmpty();
}

Answer

Your problem is that you poll the first element and don't check if the bracket is at the last position, you just check if it is in the array. Use getLast() to check if the open bracket is at the last position and pollLast() to remove the last element.

And don't return something inside the for loop. Just return the result at the end of your function. Your function validate "([)]" as true because it returns after ) and doesn't process more.

private static boolean check(String string){
        Queue<Character> chars = new LinkedList<>();
        for (Character charr: string.toCharArray()){
            if (charr.equals('{') || charr.equals('[') || charr.equals('(')){
                chars.add(charr);
            }else if (charr.equals('}') && chars.getLast().equals('{')){
                chars.pollLast();
            }else if (charr.equals(')') && chars.getLast().equals('(')){
                chars.pollLast();
            }else if (charr.equals(']') && chars.getLast().equals('[')){
                chars.pollLast();
            }
        }
        return chars.isEmpty();
    }