1. Description
Given a series of running logs of n functions, return their running time.
2. Solution
For every log, decode it into three variable, representing the function id, start/end, time.
Use a stack to store those functions that are waiting.
If the stack is not empty, add the diff between the log time and the former time(a) to the running time of the top function in the stack.
If the current operation is start, put the function into stack.
If the current operation is end, pop the top element from the stack, add 1 to its running time.
3. Code
vector<int> exclusiveTime(int n, vector<string>& logs) {
vector<int>ans(n,0);
stack<int>s;
int a = 0;
for(int i=0;i<logs.size();i++){
int id,t,order;
convert(logs[i],id,order,t);
if(!s.empty())
ans[s.top()]+=(t-a);
a=t;
if(order==0){
s.push(id);
}
else{
int x= s.top();
s.pop();
ans[x]+=1;
a++;
}
}
return ans;
}
void convert(string s,int &id,int& order,int& t){
string s1,s2,s3;
int i =0 ;
for(;i<s.size()&&s[i]!=':';i++)
s1+=s[i];
i++;
for(;i<s.size()&&s[i]!=':';i++)
s2+=s[i];
i++;
for(;i<s.size()&&s[i]!=':';i++)
s3+=s[i];
id = atoi(s1.c_str());
t = atoi(s3.c_str());
if(s2=="start")
order = 0;
else
order = 1;
}