Fast Java Solution with 20 lines


  • 1
    Z
    public class ValidParentheses {
    
    Map<Character, Character> characterMap = new HashMap<Character, Character>(){{
        put(')', '(');
        put(']', '[');
        put('}', '{');
    }};
    
    public boolean isValid(String s) {
        if (s == null || s.length() % 2 == 1) {
            return false;
        }
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char item = s.charAt(i);
            if (item == ')' || item == ']' || item == '}') {
                if (stack.isEmpty()) {
                    return false;
                }
                Character pop = stack.pop();
                if (pop != characterMap.get(item)) {
                    return false;
                }
            } else {
                stack.push(item);
            }
        }
        return stack.isEmpty();
    }
    
    public static void main(String[] args) {
        System.out.println(new ValidParentheses().isValid("{({[]})}"));
        System.out.println(new ValidParentheses().isValid("(("));
    }
    

    }


  • 0

    public boolean isValid(String s) {
    Map<Character,Character> oppsite = new HashMap<Character,Character>();
    oppsite.put('(',')');
    oppsite.put('[',']');
    oppsite.put('{','}');
    Stack<Character> temp = new Stack<Character>();
    for (char str : s.toCharArray()) {
    if(str == '('|| str == '[' || str == '{'){
    temp.push(str);
    }
    if(str == ')'|| str == ']' || str == '}'){
    if(temp.isEmpty()) return false;
    if(str == oppsite.get(temp.pop()))
    continue;
    else return false;
    }

    }
    
    return temp.isEmpty();
    

    }


Log in to reply
 

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