1233. Remove Sub-Folders from the Filesystem
- Remove Sub-Folders from the Filesystem python solution
题目描述
Given a list of folders, remove all sub-folders in those folders and return in any order the folders after removing.
If a folder[i] is located within another folder[j], it is called a sub-folder of it.
The format of a path is one or more concatenated strings of the form: / followed by one or more lowercase English letters. For example, /leetcode and /leetcode/problems are valid paths while an empty string and / are not.
解析
首先将folder按长度排序,短的在前面,长的在后面。
然后检查每个每个路径是否存在父类,若存在就跳过。若不存在,就将其添加入answer数组内。
class Solution:
def removeSubfolders(self, folder: List[str]) -> List[str]:
folder.sort(key=len)
seen = set()
for f in folder:
if not any(f[i] == '/' and f[: i] in seen for i in range(2, len(f))):
seen.add(f)
return list(seen)
Reference
https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/discuss/409028/JavaPython-3-3-methods-from-O(NlogN)-to-O(N)-w-brief-explanation-and-analysis.