JAVA solution using switch and stack


  • 0
    Y
    public class Solution {
        public boolean isValid(String s) {
            Stack<Character> stack = new Stack<Character>();
            for (char c : s.toCharArray()) {
                switch(c) {
                    case '(':
                    case '{':
                    case '[':
                        stack.push(c);
                        break;
                    case ']':
                        if (stack.isEmpty() || stack.pop() != '[') return false;
                        break;
                    case '}':
                        if (stack.isEmpty() || stack.pop() != '{') return false;
                        break;
                    case ')':
                        if (stack.isEmpty() || stack.pop() !='(') return false;
                        break;
                }
            }
            if (stack.isEmpty()) {
                return true;
            }
            return false;
        }
    }
    

  • 0
    Z

    the last statement --
    if (stack.isEmpty()) {
    return true;
    }
    return false;

    can be simplified as
    return stack.isEmpty();


Log in to reply
 

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