Use switch will be faster than if.. else..


  • 0
    C

    Use switch will be faster than if.. else..

        public boolean isValid(String s) {
            Deque<Character> stack = new ArrayDeque<>();
            for(char ch : s.toCharArray()) {
                switch(ch) {
                    case '(': stack.push(')');break;
                    case'[': stack.push(']');break;
                    case '{': stack.push('}');break;
                    default: if(stack.isEmpty() || ch != stack.pop()) return false;break;
                }
            }
            return stack.isEmpty();
        }
    

Log in to reply
 

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