jeudi 7 juillet 2016

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();
    }

Aucun commentaire:

Enregistrer un commentaire