描述
給定一個目錄信息列表(包含目錄路徑),以及該目錄中包含內容的所有文件,你需要根據路徑查找文件系統中所有重複文件組。
一組重複文件包含至少兩個具有相同內容的文件。
輸入信息列表中的單個目錄信息字符串具有如下格式:
"root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)"
這代表在目錄root/d1/d2/.../dm
中有 n 個文件 (f1.txt, f2.txt ... fn.txt
,內容分別爲 f1_content, f2_content ... fn_content
). 注意n >= 1 並且 m >= 0。 如果 m = 0, 這意味着這個目錄正好是根目錄。
輸出一個包含重複文件路徑的列表。對於每一個組,包含所有的具有相同內容的文件路徑。一個文件路徑是一個具有以下格式的字符串 A file
"directory_path/file_name.txt"
1.最終輸出不需要特定順序。
2.你可以假定目錄名稱、文件名稱和文件內容只包含字母和數字,文件內容的長度在 [1,50] 內.
3.給定的文件的數目在在[1,20000]內.
4.你可以假定在同一個目錄下,沒有文件或者目錄共享同一個名字.
5.你可以假定每一個給定的目錄信息代表一個唯一的目錄。目錄路徑和文件信息由單個空格分割。
您在真實的面試中是否遇到過這個題? 是
題目糾錯
樣例
樣例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"]]
樣例2
輸入:
["root/a 1.txt(abcd) 2.txt(efgh)"]
輸出:
[]
挑戰
1.想象給定一個真實的文件系統,你會怎樣檢索文件?DFS 還是 BFS?
2.如果文件內容十分大(GB級別),你會怎樣修改你的答案?
3.如果你只能以每單位時間1kb的速度讀入文件,你會怎樣修改你的答案?
4.你修改過的答案的事件複雜度怎麼樣?最花時間的部分和最花內存的部分分別是什麼?如何優化?
5.怎樣保證你找到的重複文件不是誤報?
public class Solution {
/**
* @param paths: a list of string
* @return: all the groups of duplicate files in the file system in terms of their paths
*/
public List<List<String>> findDuplicate(String[] paths) {
// Write your code here
HashMap<String,List<String>> hm = new HashMap<String,List<String>>();
List<List<String>> resultList = new ArrayList<List<String>>();
for (int i = 0; i < paths.length; i++)
{
String p = paths[i];
String[] pathArr = p.split(" ");
String root = pathArr[0];
for (int j = 1;j < pathArr.length;j++)
{
String s = pathArr[j];
String[] contentArr = s.split("\\(");
String fileName = contentArr[0];
String value = contentArr[1];
if(false == hm.containsKey(value))
{
List<String> ls = new ArrayList<String>();
ls.add(root + "/" +fileName);
hm.put(value,ls);
}
else
{
int n = resultList.indexOf(hm.get(value));
System.out.print(n);
hm.get(value).add(root + "/" +fileName);
if(-1 != n)
{
resultList.set(n,hm.get(value));
}
else
{
resultList.add(hm.get(value));
}
}
}
}
return resultList;
}
}