stack类似括号匹配O(n) time O(n) space
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class Solution { public: vector<int> exclusiveTime(int n, vector<string>& logs) { vector<int> res(n); stack<vector<int>> s; for (const auto &l : logs) { auto e = parse(l); if (e[1]) { int t = e[2] - s.top()[2] + 1; res[e[0]] += t; s.pop(); if (!s.empty()) { res[s.top()[0]] -= t; } } else { s.push(e); } } return res; }
vector<int> parse(const string &s) { int p1 = s.find(":"), p2 = s.find(":", p1 + 1); return {stoi(s.substr(0, p1)), s.substr(p1 + 1, p2 - p1 - 1) == "end", stoi(s.substr(p2 + 1))}; } };
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| class Solution { struct Log { Log(const string &s) { istringstream input(s); string token; getline(input, token, ':'); id = stoi(token); getline(input, e, ':'); getline(input, token, ':'); time = stoi(token); } int id; string e; int time; }; public: vector<int> exclusiveTime(int n, vector<string>& logs) { vector<int> res(n); int sz = logs.size(); stack<Log> s; for (const auto &log : logs) { Log curr(log); if (curr.e == "start") { s.push(curr); } else { Log prev = s.top(); s.pop(); int interval = curr.time + 1 - prev.time; res[prev.id] += interval; if (!s.empty()) { res[s.top().id] -= interval; } } } return res; } };
|