Easy Java Solution:)


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

Log in to reply
 

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