C++ clean solution (stack)


  • 0
    C
    vector<int> exclusiveTime(int n, vector<string>& logs) {
            vector<int> ans(n, 0);
            stack<pair<int, int>> s;
            int cur = 0;
            for(int i = 0; i < logs.size(); i++){
                int col1 = logs[i].find(":");
                int col2 = logs[i].find(":", col1 + 1);
                int id = stoi(logs[i].substr(0, col1));
                int time = stoi(logs[i].substr(col2 + 1));
                string state = logs[i].substr(col1 + 1, col2 - col1 - 1);
                if(state == "start")
                    s.push({id, time});
                else{
                    int start_time = s.top().second;
                    s.pop();
                    int duration = time - start_time + 1;
                    ans[id] += duration;
                    if (!s.empty()) 
                        ans[s.top().first] -= duration;
                }
            }
            return ans;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.