python solution that beat 100% for now.


  • 0
    Y
    import re
    
    class Solution(object):
        def exclusiveTime(self, n, logs):
            """
            :type n: int
            :type logs: List[str]
            :rtype: List[int]
            """
    
            # TODO convert start/end to number encoding to avoid string comparison in later tests.
            pattern = re.compile('(\d+):(start|end):(\d+)')
            call_stack = []
            time_counter = [0] * n
            active_fn_enter_time = None  # from the VERY BEGINNING of {time}
    
            for log in logs:
                fn_id, action, time = pattern.match(log).groups()
                fn_id = int(fn_id)
                time = int(time)
    
                active_fn_id = call_stack[-1] if call_stack else None
                # TODO use mechanism other than string equality test for better performance
                if action == 'end':
                    assert fn_id == active_fn_id
                    time_counter[active_fn_id] += time + 1 - active_fn_enter_time
                    call_stack.pop()
                    active_fn_enter_time = time + 1
                else:               # action == 'start'
                    if not active_fn_id is None:
                        time_counter[active_fn_id] += time - active_fn_enter_time
    
                    call_stack.append(fn_id)
                    active_fn_enter_time = time
    
            return time_counter
    

Log in to reply
 

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