Easy solution with one stack and one hashmap for mapping storage


  • 0
    T

    '''
    public class Solution {
    HashMap<Character, Character> map = new HashMap<Character, Character>();

    void createMapping() {
        map.put(']', '[');
        map.put('}', '{');
        map.put(')', '(');
    }
    
    public boolean isValid(final String name) {
        createMapping();
        Stack<Character> stack = new Stack<Character>();
        for (int i = 0; i < name.length(); i++) {
            char val = name.charAt(i);
            if (map.containsKey(val)) {
                if (stack.isEmpty()) {
                    return false;
                } else {
                    if (!stack.pop().equals(map.get(val))) {
                        return false;
                    }
                }
            } else {
                stack.push(val);
            }
        }
        return stack.isEmpty();
    }
    

    }
    '''


Log in to reply
 

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