LeetCode 题解工作台
删除子文件夹
你是一位系统管理员,手里有一份文件夹列表 folder ,你的任务是要删除该列表中的所有 子文件夹 ,并以 任意顺序 返回剩下的文件夹。 如果文件夹 folder[i] 位于另一个文件夹 folder[j] 下,那么 folder[i] 就是 folder[j] 的 子文件夹 。 folder[j]…
4
题型
6
代码语言
3
相关题
当前训练重点
中等 · 数组·string
答案摘要
我们先将数组 `folder` 按照字典序排序,然后遍历数组,对于当前遍历到的文件夹 ,如果它的长度大于等于答案数组中最后一个文件夹的长度,并且它的前缀包含答案数组的最后一个文件夹再加上一个 `/`,则说明 是答案数组中最后一个文件夹的子文件夹,我们不需要将其加入答案数组中。否则,我们将 加入答案数组中。 遍历结束后,答案数组中的文件夹即为题目要求的答案。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·string 题型思路
题目描述
你是一位系统管理员,手里有一份文件夹列表 folder,你的任务是要删除该列表中的所有 子文件夹,并以 任意顺序 返回剩下的文件夹。
如果文件夹 folder[i] 位于另一个文件夹 folder[j] 下,那么 folder[i] 就是 folder[j] 的 子文件夹 。folder[j] 的子文件夹必须以 folder[j] 开头,后跟一个 "/"。例如,"/a/b" 是 "/a" 的一个子文件夹,但 "/b" 不是 "/a/b/c" 的一个子文件夹。
文件夹的「路径」是由一个或多个按以下格式串联形成的字符串:'/' 后跟一个或者多个小写英文字母。
- 例如,
"/leetcode"和"/leetcode/problems"都是有效的路径,而空字符串和"/"不是。
示例 1:
输入:folder = ["/a","/a/b","/c/d","/c/d/e","/c/f"] 输出:["/a","/c/d","/c/f"] 解释:"/a/b" 是 "/a" 的子文件夹,而 "/c/d/e" 是 "/c/d" 的子文件夹。
示例 2:
输入:folder = ["/a","/a/b/c","/a/b/d"] 输出:["/a"] 解释:文件夹 "/a/b/c" 和 "/a/b/d" 都会被删除,因为它们都是 "/a" 的子文件夹。
示例 3:
输入: folder = ["/a/b/c","/a/b/ca","/a/b/d"] 输出: ["/a/b/c","/a/b/ca","/a/b/d"]
提示:
1 <= folder.length <= 4 * 1042 <= folder[i].length <= 100folder[i]只包含小写字母和'/'folder[i]总是以字符'/'起始folder每个元素都是 唯一 的
解题思路
方法一:排序
我们先将数组 folder 按照字典序排序,然后遍历数组,对于当前遍历到的文件夹 ,如果它的长度大于等于答案数组中最后一个文件夹的长度,并且它的前缀包含答案数组的最后一个文件夹再加上一个 /,则说明 是答案数组中最后一个文件夹的子文件夹,我们不需要将其加入答案数组中。否则,我们将 加入答案数组中。
遍历结束后,答案数组中的文件夹即为题目要求的答案。
时间复杂度 ,空间复杂度 。其中 和 分别为数组 folder 的长度和数组 folder 中字符串的最大长度。
class Solution:
def removeSubfolders(self, folder: List[str]) -> List[str]:
folder.sort()
ans = [folder[0]]
for f in folder[1:]:
m, n = len(ans[-1]), len(f)
if m >= n or not (ans[-1] == f[:m] and f[m] == '/'):
ans.append(f)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(N \times L) |
| 空间 | O(N \times L) |
面试官常问的追问
外企场景- question_mark
Look for understanding of sorting techniques and their applications in path comparison.
- question_mark
Expect candidates to demonstrate a clear approach to handling nested structures with efficient filtering.
- question_mark
Assess whether the candidate can balance time complexity with simplicity, particularly regarding sorting and iteration.
常见陷阱
外企场景- error
Not sorting the list, which can lead to incorrect results when detecting sub-folders.
- error
Forgetting to account for the '/' separator when comparing folder paths.
- error
Overcomplicating the solution with unnecessary data structures or algorithms when a simple sorting and iteration approach is sufficient.
进阶变体
外企场景- arrow_right_alt
What if folder paths have different levels of depth, or are not sorted initially?
- arrow_right_alt
How would this approach change if the folder paths could be represented in a tree structure instead of an array?
- arrow_right_alt
What if the problem extended to a scenario where sub-folders had additional metadata?