https://leetcode.com/problems/exclusive-time-of-functions/
类似于括号匹配问题,遍历 list,每一次来到新元素时,结算当前正在执行的函数已经运行的时间,累加到 result 数组的对应位置中。怎么知道当前正在执行哪个函数呢?维护函数调用栈即可,栈顶的元素就是正在执行的函数。
需要像括号匹配那样维护函数调用栈,即当遇到相同元素的 end 时,想象成括号闭合,则 pop 栈顶元素;如果不能闭合,则将当前看到的元素入栈。
需要注意的细节:start 时间点和 end 时间点的开闭区间不一样。
class Solution {
public static final int ID = 0;
public static final int STATUS = 1;
public static final int TIMESTAMP = 2;
public static final String START = "start";
public static final String END = "end";
public int[] exclusiveTime(int n, List logs) {
Stack stack = new Stack<>(); // call stack (id)
int[] result = new int[n];
for (int i = 0; i < logs.size(); i++) {
boolean paired = false;
String[] curLog = logs.get(i).split(":");
if (!stack.isEmpty()) {
String[] preLog = logs.get(i - 1).split(":");
Integer runningId = stack.peek();
int diff = Integer.parseInt(curLog[TIMESTAMP]) - Integer.parseInt(preLog[TIMESTAMP]);
if (preLog[STATUS].equals(START) && curLog[STATUS].equals(END)) diff += 1;
if (preLog[STATUS].equals(END) && curLog[STATUS].equals(START)) diff -= 1;
result[runningId] += diff;
if (curLog[STATUS].equals(END) && Integer.parseInt(curLog[ID]) == runningId) { // 成功匹配
stack.pop();
paired = true;
}
}
if (!paired) stack.push(Integer.parseInt(curLog[ID]));
}
return result;
}
}



