Java solution without stack, beats 98%


  • 0
    P
    public boolean isValid(String s) {
            if(s == null || s.length() < 1)
            {
                return false;
            }
            ArrayList<Character> arl = new ArrayList<>();
            char[] ar = s.toCharArray();
            for(int i=0; i <ar.length; i++)
            {
                switch(ar[i])
                {
                    case '}' : 
                    {
                        if(arl.isEmpty() || arl.get(arl.size()-1)!='{')
                        {
                            return false;
                        }
                        else
                        {
                            arl.remove(arl.size()-1);break;
                        }
                    }
                    case ']' :
                    {
                        if(arl.isEmpty() || arl.get(arl.size()-1)!='[')
                        {
                            return false;
                        }
                        else
                        {
                            arl.remove(arl.size()-1);break;
                        }
                    }
                    case ')' :
                    {
                        if(arl.isEmpty() || arl.get(arl.size()-1)!='(')
                        {
                            return false;
                        }
                        else
                        {
                            arl.remove(arl.size()-1);break;
                        }
                    }
                    default : arl.add(ar[i]);
                }
                
            }
            if(!arl.isEmpty())
            {
                return false;
            }
            return true;
        }
    

  • 0

    That's exactly what a stack is, you just created your own stack using an ArrayList, shouldn't be any faster than using java.util.Stack


Log in to reply
 

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