Leetcode 1598. Crawler Log Folder

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

2. Solution

**解析:**Version 1,使用数据结构栈,依次处理日志操作即可,最后栈中的元素数量即为当前在第几层子目录,因此返回根目录的次数为栈的长度。

  • Version 1
class Solution:
    def minOperations(self, logs: List[str]) -> int:
        stack = []
        for log in logs:
            if log == './':
                continue
            elif log == '../':
                if stack:
                    stack.pop()
            else:
                stack.append(log)
        return len(stack)

**解析:**Version 2,思想与1一样,直接计数即可。

  • Version 2
class Solution:
    def minOperations(self, logs: List[str]) -> int:
        count = 0
        for log in logs:
            if log == './':
                continue
            elif log == '../':
                count = max(0, count - 1)
            else:
                count += 1
        return count

Reference

  1. https://leetcode.com/problems/crawler-log-folder/

你可能感兴趣的:(Leetcode,leetcode,算法,职场和发展)