class Log {
public:
int id;
string flag;
int time;
Log(int _id, string _flag, int _time);
};
Log::Log(int _id, string _flag, int _time){
id = _id;
flag = _flag;
time = _time;
}
class Solution {
public:
vector<int> exclusiveTime(int n, vector<string>& logs) {
vector<int> ans(n); // initialize a vector of answers
stack<Log> s;
for (const string &log : logs) {
stringstream ss(log);
string temp1, temp2, temp3;
getline(ss, temp1, ':');
getline(ss, temp2, ':');
getline(ss, temp3, ':');
Log curr = Log(stoi(temp1), temp2, stoi(temp3));
if (s.empty()) {
s.push(curr);
continue;
}
Log prev = s.top();
// only two cases: 1) switch to a new process, or 2) end the current process
// 1) happens when : curr_flag = "start"
// 2) happends when : curr_flat = "end"
if (curr.flag == "start") {
// hold the previous process, and add time to it's answer
int pos = prev.id;
int delta = curr.time - prev.time;
ans[pos] += delta;
s.push(curr);
}
else {
// end this process
int pos = prev.id;
int delta = curr.time - prev.time + 1;
ans[pos] += delta;
// remove from stack
s.pop();
// if there is a process in stack, set it running at the next time stamp
if (!s.empty()) s.top().time = curr.time + 1;
}
}
return ans;
}
};
With class and string manipulation.
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.