Short concise Java solution.


  • 0
    B
    public class Solution {
        
        private static final HashMap<Character, Character> map;
        
        static {
            map = new HashMap<>();
            map.put(')', '(');
            map.put(']', '[');
            map.put('}', '{');
        }
        
        public boolean isValid(String s) {
            Stack<Character> parentheses = new Stack<>();
            for (char c : s.toCharArray()) {
                if (c == '(' || c == '[' || c == '{') {
                    parentheses.push(c);
                } else if (c == ')' || c == ']' || c == '}') {
                    if (parentheses.isEmpty() || !map.get(c).equals(parentheses.pop())) {
                        return false;
                    }
                }
            }
            return parentheses.isEmpty();
        }
    }
    

Log in to reply
 

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