Easy java solution with comments using O(n) space beats 90% of submissions.


  • 0
    D
    class Solution {
        public int calPoints(String[] ops) {
            
            //Base case: if ops array is null or length 0, return 0
            if(ops == null || ops.length==0)
                return 0;
            
            //General case: if 1 or more entries are present in ops[]
            //array to keep track of points in each round
            int[] points=new int[ops.length];
            
            //indices to keep track of last 2 valid rounds
            int lastValidIndex1=-1;
            int lastValidIndex2=-1;
            
            //for loop to iterate through the array
            
            for(int i=0;i<ops.length;i++)
            {
                //Case 1: if ops[i] is D
                if(ops[i].equals("D"))
                {
                    points[i]=2*points[lastValidIndex1];
                    
                    //update lastValidIndices
                    lastValidIndex2=lastValidIndex1;
                    lastValidIndex1=i;
                }
                
                //Case 2: if ops[i] is C
                else if(ops[i].equals("C"))
                {
                    points[i]=0;
                    points[lastValidIndex1]=0;
                    
                    //update lastValidIndices
                    lastValidIndex1=lastValidIndex2;
                    
                    lastValidIndex2--;
                    while(lastValidIndex2>=0 && points[lastValidIndex2]==0)
                        lastValidIndex2--;
                    
                }
                
                //Case 3: if ops[i] is +
                else if(ops[i].equals("+"))
                {
                    points[i]=points[lastValidIndex1]+points[lastValidIndex2];
                    
                    //update lastValidIndices
                    lastValidIndex2=lastValidIndex1;
                    lastValidIndex1=i;
                }
                
                //Case 4: if ops[i] is a number
                else
                {
                    points[i]=Integer.parseInt(ops[i]);
                    
                    //update lastValidIndices
                    lastValidIndex2=lastValidIndex1;
                    lastValidIndex1=i;
                }
            }
            
            //compute the result
            int result=0;
            
            for(int i:points)
                result+=i;
            
            return result;
            
        }
    }
    

Log in to reply
 

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