Simple Java Solution


  • 5
    A
    public class Solution {
        public boolean isValid(String s) {
            if(s == null || s.isEmpty()){
                return true;
            }
            if (s.length() % 2 != 0){
                return false;
            }
            Stack<Character> stack = new Stack<Character>();
            
            for (int i = 0 ; i < s.length(); i++){
                if (s.charAt(i) == '{' || s.charAt(i) == '(' || s.charAt(i) == '['){
                    stack.push(s.charAt(i));
                }
                else if (s.charAt(i) == '}'){
                    if(!stack.isEmpty()){
                        if (stack.pop() != '{'){
                            return false;
                        }
                    }
                    else {
                        return false;
                    }
                }
                else if (s.charAt(i) == ')'){
                    if(!stack.isEmpty()){
                        if (stack.pop() != '('){
                            return false;
                        }
                    }
                    else {
                        return false;
                    }
                }
                else if (s.charAt(i) == ']'){
                    if(!stack.isEmpty()){
                        if (stack.pop() != '['){
                            return false;
                        }
                    }
                    else {
                        return false;
                    }
                }
            }
            if(stack.isEmpty()){
                return true;
            }
            return false;
            
        }
    }

Log in to reply
 

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