Java use HashMap to simplify the code


  • 0

    This simplied statements in for loop, however it has overhead of map.put(..)

      public class Solution {
            public boolean isValid(String expression) {
                if (expression == null) {
                    return true;
                }
                Map<Character, Character> map = new HashMap<>();
                map.put(')', '(');
                map.put(']', '[');
                map.put('}', '{');
                Stack<Character> stack = new Stack<>();
                for (char symbol : expression.toCharArray()) {
                    if (!map.containsKey(symbol)) {
                        stack.push(symbol);
                    } else if (stack.isEmpty() || stack.pop() != map.get(symbol)) {
                        return false;
                    }
                }
                return stack.isEmpty();
            }
        }

Log in to reply
 

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