Elegant java solution.


  • 0
    Z
    public class Solution {
        public boolean isValid(String s) {
            Map<Character, Character> map = new HashMap<>();
            map.put(')','(');
            map.put(']','[');
            map.put('}','{');
            Set<Character> set = new HashSet<>();
            set.add('(');
            set.add('[');
            set.add('{');
            Stack<Character> stack = new Stack<>();
            for(char c: s.toCharArray()){
                if(set.contains(c))stack.push(c);
                if(map.containsKey(c)){
                    if(stack.isEmpty() || stack.pop() != map.get(c))return false;
                }
            }
            return stack.size() == 0;
        }
    }
    

Log in to reply
 

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