Very concise java solution


  • 3
    M
    
    public class Solution {
        public boolean isValid(String s) {        
            
            Stack<Character> stack = new Stack<>();
            
            for (int i =0; i<s.length(); i++){
                if (s.charAt(i) == ')' && (stack.isEmpty() || stack.pop() != '(')) return false;
                if (s.charAt(i) == '}' && (stack.isEmpty() || stack.pop() != '{')) return false;
                if (s.charAt(i) == ']' && (stack.isEmpty() || stack.pop() != '[')) return false;
                if (s.charAt(i) == '{' || s.charAt(i) == '(' || s.charAt(i) == '[') stack.push(s.charAt(i));
            }
            return stack.isEmpty();
        }
    }

Log in to reply
 

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