Java Stack Solution

  • 0

    The key to the problem is how should we define interval?
    In the solution, I used a variable prev to store the previous node timestamp. If the previous node is a start, means it belongs to the current evaluating function, then prev = start time. In contrast, if the previous node is an end, means that belongs to previous function, prev = end time + 1. In this way, we can properly deal with the interval calculation.

    class Solution {
        public int[] exclusiveTime(int n, List<String> logs) {
            if (logs == null || logs.size() == 0) return new int[0];
            int[] res = new int[n];
            Deque<Integer> stack = new ArrayDeque<>();
            int prev = 0;
            for (int i = 0; i < logs.size(); i++) {
                String[] strs = logs.get(i).split(":");
                int time = Integer.parseInt(strs[2]);
                if (strs[1].equals("start")) {
                    if (!stack.isEmpty()) {
                        stack.push(stack.pop() + time - prev);
                    prev = time;
                } else if (strs[1].equals("end")) {
                    int index = Integer.parseInt(strs[0]);
                    prev = time + 1;
            return res;

Log in to reply

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