【leetcode】636. Exclusive Time of Functions

题目如下:

解题思路:本题和括号匹配问题有点像,用栈比较适合。一个元素入栈前,如果自己的状态是“start”,则直接入栈;如果是end则判断和栈顶的元素是否id相同并且状态是“start”,如果满足这两个条件,则说明这个元素和栈顶的元素是配对的,栈顶元素出栈。但是这个函数的的执行时间却不能简单的用end-start,因为这个函数里面可以还调用了其他函数,需要减去这些内部调用函数的执行时间,这里就需要引入一个新的变量来保存内部调用函数的执行时间。这个时间也很好求,函数完成配对后,栈顶元素出栈,只要把end-start累加到新的栈顶元素的内部调用函数执行时间即可。

代码如下:

class Solution(object):
    def exclusiveTime(self, n, logs):
        """
        :type n: int
        :type logs: List[str]
        :rtype: List[int]
        """
        stack = []
        res = [0] * n
        for i in logs:
            id,status,time = i.split(':')
            if status == 'start' or len(stack) == 0 or stack[-1][0] != id:
                stack.append([id,status,time,0])
            else:
                executetime = int(time) - int(stack[-1][2]) - int(stack[-1][3]) + 1
                res[int(stack[-1][0])] += executetime
                executerange = int(time) - int(stack[-1][2])
                #ex = res[int(stack[-1][0])]
                stack.pop(-1)
                if len(stack) > 0:
                    stack[-1][3] += executerange + 1
        return res
原文地址:https://www.cnblogs.com/seyjs/p/9660868.html