Easy code(c++) with explaination


  • 1
    K

    Important thing is two.

    1. Stack is used implementing function call.
      when function is start, push()
      when function is end, pop()
      and the current function is top().

    2. Let's define the timestamp with cmd "start" is A and with cmd "end" is B.
      then, exclusive time have 4 cases
      [A, A'), [A, B], (B, A), (B, B']

    A is alway open at start point
    A is alway close at end point
    B is alway close at start point
    B is alway open at end point

    generaly Y - X means the length of [X, Y)

    so, in my code
    I made an end point open']' by inc exclusive_time when cmd is 'end'. (1)
    and also I made start point close'(' by inc last_time when last cmd is 'end'.(2)

    
    
    class Solution {
    private:
    	void parselog(string& s, int& log_id, int& time, string& cmd)
    	{	
    		int first = s.find(':');
    		int second = s.find(':' , first + 1);
    		log_id = stoi(s.substr(0, first));
    		cmd = s.substr(first + 1, second - (first + 1));
    		time = stoi(s.substr(second + 1));
    	}
    public:
    	vector<int> exclusiveTime(int n, vector<string>& logs) 
    	{
    		vector<int> ret(n,0);
    		stack<int> st;
    		if (logs.empty())return ret;
    		string cmd = "";
    		int log_id = -1;
    		int end_point = -1;
    		int start_point = 0;
    		parselog(logs[0], log_id, start_point, cmd);
    		st.push(log_id);
    		for (int j = 1 ; j < logs.size(); j++)
    		{
    			parselog(logs[j], log_id, end_point, cmd);
    			int working_time = end_point - start_point + (cmd == "end");//(1)
    			ret[st.top()] += working_time;
    			if (cmd == "start")st.push(log_id);
    			else st.pop();
    			start_point = end_point + (cmd == "end");//(2)
    		}
    		return ret;
    	}
    };
    

Log in to reply
 

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