636. Exclusive Time of Functions!

class Solution {
    public int[] exclusiveTime(int n, List<String> logs) {
        // when the execution of fuction is end or suspended, 
        // add the execution time to result
        int[] result = new int[n];
        // stack to track the index of each functions
        Deque<Integer> stack = new LinkedList<>();
        
        int preTime=0;
        for(String log: logs){
            // String.split(string s);
            String[] parts = log.split(":");
            // convert string to int
            // Integer.parseInt(String S);
            // important: add 1 to the endTime 
            int currentTime = parts[1].equals("end") ? Integer.parseInt(parts[2])+1 : Integer.parseInt(parts[2]);
            if (stack.size()>0) result[stack.peek()]+=currentTime-preTime;
            preTime = currentTime;
            
            if(parts[1].equals("start")){
                stack.push(Integer.parseInt(parts[0]));
            }else{
                stack.pop();
            }
        }
        
        return result;
    }
}

Last updated