1. 程式人生 > 實用技巧 >609. 在系統中查詢重複檔案

609. 在系統中查詢重複檔案

給定一個目錄資訊列表,包括目錄路徑,以及該目錄中的所有包含內容的檔案,您需要找到檔案系統中的所有重複檔案組的路徑。一組重複的檔案至少包括二個具有完全相同內容的檔案。

輸入列表中的單個目錄資訊字串的格式如下:

"root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)"

這意味著有 n 個檔案(f1.txt,f2.txt...fn.txt 的內容分別是 f1_content,f2_content...fn_content)在目錄root/d1/d2/.../dm下。注意:n>=1 且 m>=0。如果 m=0,則表示該目錄是根目錄。

該輸出是重複檔案路徑組的列表。對於每個組,它包含具有相同內容的檔案的所有檔案路徑。檔案路徑是具有下列格式的字串:

"directory_path/file_name.txt"

示例 1:

輸入:
["root/a 1.txt(abcd) 2.txt(efgh)", "root/c 3.txt(abcd)", "root/c/d 4.txt(efgh)", "root 4.txt(efgh)"]
輸出:
[["root/a/2.txt","root/c/d/4.txt","root/4.txt"],["root/a/1.txt","root/c/3.txt"]]

注:

最終輸出不需要順序。
您可以假設目錄名、檔名和檔案內容只有字母和數字,並且檔案內容的長度在 [1,50] 的範圍內。

給定的檔案數量在 [1,20000] 個範圍內。
您可以假設在同一目錄中沒有任何檔案或目錄共享相同的名稱。
您可以假設每個給定的目錄資訊代表一個唯一的目錄。目錄路徑和檔案資訊用一個空格分隔。

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/find-duplicate-file-in-system

很明顯用hashmap

var findDuplicate = function(paths) {
  const hashmap = {};

  for (let path of paths) {
    const [folder, ...files] = path.split(" ");
    
for (let file of files) { const l = file.indexOf("("); const r = file.lastIndexOf(")"); const filename = file.slice(0, l); const content = file.slice(l, r); const fullname = `${folder}/${filename}`; if (!hashmap[content]) hashmap[content] = []; hashmap[content].push(fullname); } } return Object.values(hashmap).filter(q => q.length >= 2);//過濾掉length==1的,確保返回的是重複的 };