Java Solution beats 98%


  • 1
    P
    public class Solution {
        public boolean isValid(String s) {
            String brackets = "(){}[]";
            char[] array = s.toCharArray();
            Stack<Integer> stack = new Stack<Integer>();
            
            int index = 0;
            for (int i=0; i<s.length(); i++) {
                index = brackets.indexOf(array[i]);
                if (index == 0 || index == 2 || index == 4) {
                    stack.push(index);
                }    
                
                if (index == 1 || index == 3 || index == 5) { 
                    if (stack.empty()||stack.pop()+1!= index) return false;
                }
                    
                    
            }
            
            return stack.empty(); 
        }
        
    }
    

Log in to reply
 

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