[JAVA] solution with HashMap to avoid condition causes


  • 0
    C

    if(s==null || s.length()==0) return true;

        Stack<Character> stack = new Stack<Character>();
        HashMap<Character, Character> map = new HashMap<Character, Character>();
        map.put(')', '(');
        map.put(']', '[');
        map.put('}', '{');
        
        for(int i=0; i<s.length(); i++) {
            char c = s.charAt(i);
            
            if(c==')' || c==']' || c=='}') {
                if(stack.isEmpty() || stack.peek()!=map.get(c))  
                    return false;
                stack.pop();
            }
            else
                stack.push(c);
        }
        
        return stack.isEmpty();

  • 0
    T

    Did you use the fact that when auto-boxing ASCII chars the Character objects returned for them will be always the same objects? If not see Character.valueOf, and consider using peek().equals( to prevent mismatches for Unicode characters. Same stands for all wrapper classes. Alternatively explicitly unbox both sides: (char)stack.peek()!=(char)map.get(.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.