BiruLyu
7/18/2017 - 2:12 AM

636. Exclusive Time of Functions(#).java

public class Solution {
    public int[] exclusiveTime(int n, List<String> logs) {
        int[] results = new int[n];
        Stack<Integer> stack = new Stack<>();
        int t = 0;
        for (String log : logs) {
            int i = log.indexOf(':');
            int j = log.lastIndexOf(':');
            int idx = Integer.parseInt(log.substring(0, i));
            int time = Integer.parseInt(log.substring(j+1));
            if (log.substring(i+1, j).equals("start")) {
                if (!stack.isEmpty()) {
                    results[stack.peek()] += time-t;
                }
                stack.push(idx);
                t = time;
            } else {
                results[stack.pop()] += time-t+1;
                t = time+1;
            }
        }
        return results;
    }
}
public class Solution {
    public int[] exclusiveTime(int n, List<String> logs) {
    int[] res = new int[n];
    Stack<Integer> stack = new Stack<>();
    int prevTime = 0;
    for (String log : logs) {
        String[] parts = log.split(":");
        if (!stack.isEmpty()) res[stack.peek()] +=  Integer.parseInt(parts[2]) - prevTime; 
        prevTime = Integer.parseInt(parts[2]);
        if (parts[1].equals("start")) stack.push(Integer.parseInt(parts[0]));
        else {
            res[stack.pop()]++;
            prevTime++;
        }
    }
    return res;
    }
}