Simple python code


  • 0
    Z
    class Solution(object):
        def exclusiveTime(self, n, logs):
            """
            :type n: int
            :type logs: List[str]
            :rtype: List[int]
            """
            #
            # There are a lot of pitfalls in this test
            # 1. (a) prev= start, cur = end (b) prev= start, cur =start
            #    (c) prev = end, cur = start (d) prev = end, cur = end
            # 2. for case: prev= end, cur=start, there might be some interval inbetween. This time interval
            # would run the last function in the start mode; we need to use stack to keep track of that
            # 
            #
            ret = [0 for _ in range(n)]
            #dict_function = {}
            stack = [logs[0]]
            for i in range(1,len(logs)):
                prev = logs[i-1].split(':')
                cur = logs[i].split(':')
                if prev[1]=='start' and cur[1]=='start':
                    stack.append(logs[i])
                    ret[int(prev[0])]+=int(cur[2])-int(prev[2])
                if prev[1]=='start' and cur[1]=='end':
                    ret[int(prev[0])]+=int(cur[2])-int(prev[2])+1
                    stack.pop()
                if prev[1]=='end' and cur[1]=='end':
                    ret[int(cur[0])]+=int(cur[2])-int(prev[2])
                    stack.pop()
                if prev[1]=='end' and cur[1]=='start':
                    if len(stack)!=0:
                        ret[int(stack[-1].split(':')[0])]+=int(cur[2])-int(prev[2])-1
                    stack.append(logs[i])    
            return ret

Log in to reply
 

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