⚡Flashcard Drill➔
NeetCode #358LC-71MediumStackNC 250
← Back to All Problems

#358 · #71 · Simplify Path(简化路径)

📌 Problem Statement & Constraints

Given an absolute Unix-style path, simplify it to its canonical form: it must start with a single /, contain no . or .. components, no double slashes, and no trailing slash (except for the root). Constraints: 1 <= path.length <= 3000.

💡 Core Algorithmic Approaches

  1. Split on / and process the components with a stack.
  2. Empty components (from //) and . components are skipped.
  3. .. pops the stack if it is non-empty; on an empty stack it is a no-op (you cannot go above the root).
  4. Join the surviving components with / and prepend a leading slash.

💻 Benchmark Python3 Implementation

class Solution:
    def simplifyPath(self, path: str) -> str:
        st = []
        for part in path.split("/"):
            if part == "" or part == ".":
                continue                   # skip empties and the current directory
            if part == "..":
                if st:
                    st.pop()               # go up one level, but not above the root
            else:
                st.append(part)
        return "/" + "/".join(st)

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): one pass over the components.
💾 Space Complexity
O(n) for the stack.

⚠️ Interview Pitfalls & Follow-ups

  • Popping on .. without the emptiness guard: st.pop() on an empty list raises IndexError; going above the root must be a no-op.
  • Treating . as a directory: it must be skipped.
  • Forgetting to skip empty components: split('/') on "//" yields empty strings, which would create empty path segments.
  • Returning "/".join(st) without the leading slash: the result must be absolute.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Stack Problems

中文速览与面试要点

简化路径

给你一个字符串 path,表示指向某一文件或目录的 Unix 风格 绝对路径 (以 / 开头),请你将其转化为更加简洁的规范路径。在 Unix 风格的文件系统中,一个点 . 表示当前目录本身;此外,两个点 .. 表示将目录切换到上一级(指向父目录);两者都可以是复杂相对路径的组成部分。任意多个连续的斜杠(即 // )都被视为单个斜杠 / 。对于此问题,任何其他格式的点(例如 ... )均被视为文件/目录名称。请注意,返回的 规范路径 必须遵循下述格式:始终以斜杠 / 开头;两个目录名之间必须只有一个斜杠 / ;最后一个目录名(如果存在) 不能 以 / 结尾;此外,路径仅包含从根目录到目标文件或目录的路径上的目录(即,不含 . 或 .. )。返回简化后得到的 规范路径 。约束:1 ≤ path.length ≤ 3000;path 由英文字母、数字、 / 、 _ 、 . 和 - 组成;path 是一个有效的 Unix 风格绝对路径。

核心要点

  • 按 / 切分 + 栈(标准解) :用 path.split("/") 切分,遍历每个部分:空串或 . 则跳过; .. 则弹出栈顶(栈空则忽略);其他则入栈。
  • 为什么用栈 : .. 是「回到上一级」,天然对应栈的弹出操作。
  • 拼接结果 : "/" + "/".join(stack) 。注意根目录时栈为空,结果为 "/" 。
  • 为什么连续斜杠会被自动处理 : split("/") 会把连续斜杠之间的内容切成空串,而空串会被跳过。

常见陷阱

  • 栈空时执行 .. 的 pop :在根目录下 .. 无效果,必须判断 if stack ,否则 IndexError。
  • 把 ... 也当成 .. 处理 :题目明确「任何其他格式的点均被视为文件/目录名称」,因此只有恰好 .. 才是上级。
  • 忘记处理连续斜杠 : split("/") 产生的空串必须跳过。
  • 结果未以 / 开头 :必须手动拼接前导斜杠,或对栈为空的情况返回 "/" 。

参考实现

class Solution:
    def simplifyPath(self, path: str) -> str:
        stack = []
        for part in path.split('/'):
            if part == '' or part == '.':
                continue                # 空串(连续斜杠)与当前目录 -> 跳过
            if part == '..':
                if stack:
                    stack.pop()         # 回到上一级(已在根目录则忽略)
            else:
                stack.append(part)      # 普通目录名
        return '/' + '/'.join(stack)    # 根目录时返回 "/"