My java solution by using stack.


  • 0
    Z
    public class Solution {
        public boolean isValid(String s) {
            Stack<Character> stack = new Stack<>();
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if(!stack.empty()) {
                    switch(c) {
                        case ')' :  if(stack.pop() != '(') return false;
                                    break;
                        case '}' :  if(stack.pop() != '{') return false;
                                    break;
                        case ']' :  if(stack.pop() != '[') return false;
                                    break;
                        default  :  stack.push(c);
                                    break;
                    }
                } else {
                    stack.push(c);
                }
            }
            return stack.isEmpty() == true;
        }
    }
    

Log in to reply
 

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