636. Exclusive Time of Functions

public: vector<int> exclusiveTime(int n, vector<string>& logs) { vector<int> ans(n); // initialize a vector of answers stack<vector<string>> s; // every element in the stack is a 2-element vector // with the first element being id, second element being time for (const string &log : logs) { unsigned int first_colon = log.find(':'); // position of first colon unsigned int second_colon = log.find(':', first_colon + 1); // position of second colon string curr_id = log.substr(0, first_colon); string curr_flag = log.substr(first_colon + 1, second_colon - first_colon - 1); string curr_time = log.substr(second_colon + 1); // find if start or end vector<string> curr = {curr_id, curr_flag, curr_time}; if (s.empty()) { s.push(curr); continue; } // else, already process running string prev_id = s.top()[0]; // who is the last process? string prev_flag = s.top()[1]; string prev_time = s.top()[2]; // 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" // we should also check for ID, but assume we have all correct input there is no need to check ID if (curr_flag == "start") { // hold the previous process, and add time to it's answer int pos = stoi(prev_id); int delta = stoi(curr_time) - stoi(prev_time); ans[pos] += delta; s.push(curr); } else { // end this process int pos = stoi(prev_id); int delta = stoi(curr_time) - stoi(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()[2] = to_string(stoi(curr_time) + 1); } } return ans; } };
Version 1: Not familiar with 1) string manipulation and 2) class definition. Rewrote with them.

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.