1. 程式人生 > 實用技巧 >1233. Remove Sub-Folders from the Filesystem

1233. Remove Sub-Folders from the Filesystem

Given a list of folders, remove all sub-folders in those folders and return inany orderthe folders after removing.

If afolder[i]is located withinanotherfolder[j], it is called asub-folderof it.

The format of a path isone or more concatenated strings of the form:/followed by one or more lowercase English letters. For example,/leetcode

and/leetcode/problemsare valid paths while an empty string and/are not.

給一堆檔案列表,刪掉所有的子資料夾。給出最後剩下的資料夾路徑

這個其實只需要安字典序排序,然後判斷i和i+1是不是包含關係就可以了,如果包含,就丟棄i+1,繼續往後看,如果不包含,那i和i+2,i+3也不可能是包含關係了,就可以把i+1也加到答案裡去,接下來去判斷i+1和後面的是否包含,重複這個過程。有個比較需要注意的地方是,如果判斷i是i+1的上層目錄,除了判斷s1 == s2[:len(s1)]以外還要判斷s2[len(s1)]是不是'/'。

class
Solution(object): def removeSubfolders(self, folder): """ :type folder: List[str] :rtype: List[str] """ folder = sorted(folder) ans = [] for f in folder: if len(ans) == 0 or ans[-1] != f[:len(ans[-1])] or f[len(ans[-1])] != '/': ans.append(f)
return ans