Re: [閒聊] 每日leetcode

看板Marginalman作者 (JerryChung)時間1年前 (2024/10/25 12:57), 編輯推噓3(300)
留言3則, 3人參與, 1年前最新討論串1043/1548 (看更多)
https://leetcode.com/problems/remove-sub-folders-from-the-filesystem 1233. Remove Sub-Folders from the Filesystem 給一個資料夾列表 folder 把裡面的子資料夾刪除後回傳 可以以任何順序回傳 folder[i] 是 folder[j] 的子資料夾代表是以 folder[j] 開頭且後面接著 "/" 如 "/a/b" 是 "/a" 的子資料夾 "/b" 不是 "/a/b/c" 的子資料夾 路徑由 '/' 加上一個或多個小寫英文字母 Example 1: Input: folder = ["/a","/a/b","/c/d","/c/d/e","/c/f"] Output: ["/a","/c/d","/c/f"] Explanation: "/a/b" 是 "/a" 的子資料夾 "/c/d/e" 是 "/c/d" 的子資料夾 Example 2: Input: folder = ["/a","/a/b/c","/a/b/d"] Output: ["/a"] Explanation: "/a/b/c" 和 "/a/b/d" 都是 "/a" 的子資料夾 Example 3: Input: folder = ["/a/b/c","/a/b/ca","/a/b/d"] Output: ["/a/b/c","/a/b/ca","/a/b/d"] Constraints: 1 <= folder.length <= 4 * 10^4 2 <= folder[i].length <= 100 folder[i] 只包含小寫英文字母跟 '/' folder[i] 總是以 '/' 開頭 每個資料夾名字是唯一的 思路: 跟題目提到的一樣 判斷是否是其他資料夾開頭並接著 '/' 然後記得要先排序 Python Code: class Solution: def removeSubfolders(self, folder: List[str]) -> List[str]: sorted_folder = sorted(folder, key=lambda x: f'{x}/') ans = [] for f in sorted_folder: if any(f'{f}/'.startswith(f'{_}/') for _ in ans): continue ans.append(f) return ans 雖然過了 不過 Runtime 也順利拿到了最末端 然後點了一下才發現 點圖可以看其他速度的 Code Sample 最快的解法差不多 但多用了 prev 更新當前查到的資料夾 就只要一層迴圈就好 class Solution: def removeSubfolders(self, folder: List[str]) -> List[str]: folder.sort() prev = '' ans = [] for f in folder: if not now or not f.startswith(f'{now}/'): ans.append(f) now = f return ans -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.45.54.91 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1729832267.A.D28.html

10/25 12:58, 1年前 , 1F
別倦了
10/25 12:58, 1F

10/25 12:59, 1年前 , 2F
大師
10/25 12:59, 2F

10/25 19:11, 1年前 , 3F
大師
10/25 19:11, 3F
文章代碼(AID): #1d6oLBqe (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1d6oLBqe (Marginalman)