Java solution using ArrayList as the stack


  • 0
    F

    We can use ArrayList as the stack to solve the question in Java.

    public boolean isValid(String s) {
        if( s.length() ==0 ) return false;
        ArrayList stack = new ArrayList();
        char[] tmp = s.toCharArray();
        
        
        try{
            
            for(int i=0;i<tmp.length;i++){
                if(tmp[i] == '('){
                    stack.add(1);
                }else if (tmp[i] == '['){
                    stack.add(2);
                }else if (tmp[i] == '{'){
                    stack.add(3);
                }else if (tmp[i] == ')'){
                    if((int)stack.get(stack.size()-1) != 1) {
                        return false;
                    }else{
                        stack.remove(stack.size() - 1);
                    }
                }else if (tmp[i] == ']'){
                    if((int)stack.get(stack.size()-1) != 2) {
                        return false;
                    }else{
                        stack.remove(stack.size() - 1);
                    }
                }else if (tmp[i] == '}'){
                    if((int)stack.get(stack.size()-1) != 3) {
                        return false;
                    }else{
                        stack.remove(stack.size() - 1);
                    }
                } 
            }
            if(stack.isEmpty()){
                return true;
            }else{
                return false;
            }
            
            
        }catch(Exception e){
            return false;
        }
          
    }
    

    }


Log in to reply
 

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