Skip to content

Commit 0fde1e4

Browse files
author
zjg23
committed
哈希表609题
1 parent 2c0fc26 commit 0fde1e4

1 file changed

Lines changed: 71 additions & 0 deletions

File tree

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
package a609;
2+
3+
import java.util.ArrayList;
4+
import java.util.HashMap;
5+
import java.util.List;
6+
import java.util.Map;
7+
8+
public class Solution {
9+
10+
/*
11+
* 输入: ["root/a 1.txt(abcd) 2.txt(efgh)", "root/c 3.txt(abcd)",
12+
* "root/c/d 4.txt(efgh)", "root 4.txt(efgh)"] 输出:
13+
* [["root/a/2.txt","root/c/d/4.txt","root/4.txt"],["root/a/1.txt",
14+
* "root/c/3.txt"]]
15+
*/
16+
17+
public List<List<String>> findDuplicate(String[] paths) {
18+
List<String> fileList = converArr(paths);
19+
20+
List<List<String>> result = new ArrayList<List<String>>();
21+
Map<String,List<String>> map = new HashMap<String,List<String>>();
22+
23+
for(String path:fileList) {
24+
String content = getContent(path);
25+
List<String> files = new ArrayList<>();
26+
if(map.containsKey(content)) {
27+
files = map.get(content);
28+
}
29+
files.add(getFile(path));
30+
map.put(content, files);
31+
}
32+
33+
for(String key:map.keySet()) {
34+
List<String> files = map.get(key);
35+
if(files.size()>1) {
36+
result.add(files);
37+
}
38+
}
39+
40+
return result;
41+
}
42+
43+
private static List<String> converArr(String[] paths){
44+
List<String> result = new ArrayList<>();
45+
for(String path:paths) {
46+
String[] tmp = path.split(" ");
47+
for(int i=1;i<tmp.length;i++)
48+
{
49+
result.add(tmp[0]+"/"+tmp[i]);
50+
}
51+
}
52+
return result;
53+
}
54+
55+
private static String getContent(String path) {
56+
int begin = path.indexOf("(");
57+
int end = path.indexOf(")");
58+
return path.substring(begin+1, end);
59+
}
60+
61+
private static String getFile(String path) {
62+
int begin = path.indexOf("(");
63+
return path.substring(0, begin);
64+
}
65+
66+
public static void main(String[] args) {
67+
String[] paths = new String[] {"root/a 1.txt(abcd) 2.txt(efgh)", "root/c 3.txt(abcd)", "root/c/d 4.txt(efgh)", "root 4.txt(efgh)"};
68+
System.out.println(new Solution().findDuplicate(paths));
69+
}
70+
71+
}

0 commit comments

Comments
 (0)