636. Exclusive Time of Functions
636. Exclusive Time of Functions

思路
函数按照时间顺序执行就是一个调用栈的结构,因此这是一道简单运用栈按照题目说明进行模拟函数调用的题目,主要的坑在于花费时间的计算,看清题意
Solution
#include <sstream>
using namespace std;
class Solution {
public:
vector<int> exclusiveTime(int n, vector<string>& logs) {
vector<int> res(n, 0);
stack<pair<int, int>> st;
string sno;
string state;
string time;
int id;
int t;
for(string s : logs) {
// 分割日志字符串
stringstream ss (s);
getline(ss, sno, ':');
getline(ss, state, ':');
getline(ss, time, ':');
id = stoi(sno);
t = stoi(time);
if (state == "start") {
// 开始调用,进栈
st.push(make_pair(id, t));
} else {
auto p = st.top();
st.pop();
// start 是那一时刻的头,end 是结束时刻的尾
t = t - p.second + 1;
res[p.first] += t;
// 上层的函数时间需要去掉中间运行的函数的时间
if (!st.empty())
res[st.top().first]-=t;
}
}
return res;
}
};
收获
巩固了 stl 的字符串基础操作
#stack #string