LeetCode 题解工作台

文件夹操作日志搜集器

每当用户执行变更文件夹操作时,LeetCode 文件系统都会保存一条日志记录。 下面给出对变更操作的说明: "../" :移动到当前文件夹的父文件夹。如果已经在主文件夹下,则 继续停留在当前文件夹 。 "./" :继续停留在当前文件夹 。 "x/" :移动到名为 x 的子文件夹中。题目数据 保证总是…

category

3

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 栈·状态

bolt

答案摘要

直接模拟,记录深度的变化即可。 时间复杂度 ,空间复杂度 。其中 为 `logs` 的长度。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 栈·状态 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

每当用户执行变更文件夹操作时,LeetCode 文件系统都会保存一条日志记录。

下面给出对变更操作的说明:

  • "../" :移动到当前文件夹的父文件夹。如果已经在主文件夹下,则 继续停留在当前文件夹
  • "./" :继续停留在当前文件夹
  • "x/" :移动到名为 x 的子文件夹中。题目数据 保证总是存在文件夹 x

给你一个字符串列表 logs ,其中 logs[i] 是用户在 ith 步执行的操作。

文件系统启动时位于主文件夹,然后执行 logs 中的操作。

执行完所有变更文件夹操作后,请你找出 返回主文件夹所需的最小步数

 

示例 1:

输入:logs = ["d1/","d2/","../","d21/","./"]
输出:2
解释:执行 "../" 操作变更文件夹 2 次,即可回到主文件夹

示例 2:

输入:logs = ["d1/","d2/","./","d3/","../","d31/"]
输出:3

示例 3:

输入:logs = ["d1/","../","../","../"]
输出:0

 

提示:

  • 1 <= logs.length <= 103
  • 2 <= logs[i].length <= 10
  • logs[i] 包含小写英文字母,数字,'.''/'
  • logs[i] 符合语句中描述的格式
  • 文件夹名称由小写英文字母和数字组成
lightbulb

解题思路

方法一:模拟

直接模拟,记录深度的变化即可。

时间复杂度 O(n)O(n),空间复杂度 O(1)O(1)。其中 nnlogs 的长度。

1
2
3
4
5
6
7
8
9
10
class Solution:
    def minOperations(self, logs: List[str]) -> int:
        ans = 0
        for v in logs:
            if v == "../":
                ans = max(0, ans - 1)
            elif v[0] != ".":
                ans += 1
        return ans
speed

复杂度分析

指标
时间O(n)
空间O(n)
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidates may struggle with handling redundant operations like './' and '../'.

  • question_mark

    Watch for efficient stack operations and correct handling of the root folder.

  • question_mark

    Evaluate if the candidate can explain their reasoning for using a stack to manage folder navigation.

warning

常见陷阱

外企场景
  • error

    Failing to handle redundant './' operations.

  • error

    Incorrectly managing folder navigation when attempting to move up from the root folder.

  • error

    Not resetting or updating the stack correctly after each operation.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Modify the problem to support a different folder structure (e.g., nested folders).

  • arrow_right_alt

    Change the operations to include invalid paths and check for error handling.

  • arrow_right_alt

    Add operations that represent folder creation or deletion and track changes accordingly.

help

常见问题

外企场景

文件夹操作日志搜集器题解:栈·状态 | LeetCode #1598 简单