Steward
分享是一種喜悅、更是一種幸福
程式語言 - LeetCode - CPP - 636. Exclusive Time of Functions
題目:

解答:
class Solution {
public:
vector<int> exclusiveTime(int n, vector<string>& logs) {
stack<int> st;
vector<int> ans(n, 0);
int pre_tmp = 0;
for (string& s : logs) {
int n0 = s.find(':');
int id = stoi(s.substr(0, n0));
int n1 = s.find(':', n0 + 1);
bool start = s.substr(n0 + 1, n1 - n0 - 1) == "start" ? true : false;
int tmp = stoi(s.substr(n1 + 1));
if (start) {
if (!st.empty()) {
ans[st.top()] += tmp - pre_tmp;
}
st.push(id);
pre_tmp = tmp;
}
else {
ans[st.top()] += tmp - pre_tmp + 1;
st.pop();
pre_tmp = tmp + 1;
}
}
return ans;
}
};