|
| 1 | +package com.v0ex.leetcode; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.List; |
| 6 | +import java.util.Map; |
| 7 | + |
| 8 | +/** |
| 9 | + * Find Duplicate File in System |
| 10 | + * |
| 11 | + * @author bugcoder |
| 12 | + */ |
| 13 | +public class LeetCode_609_49 { |
| 14 | + |
| 15 | + /** |
| 16 | + * 用哈希表来处理,key就是文件的内容,value就是文件的路径 |
| 17 | + * @param paths |
| 18 | + * @return |
| 19 | + */ |
| 20 | + public List<List<String>> findDuplicate(String[] paths) { |
| 21 | + Map<String,List<String>> map = new HashMap<>(); |
| 22 | + for (String path : paths) { |
| 23 | + String[] split = path.split(" "); |
| 24 | + String rootPath = split[0]+"/"; |
| 25 | + for (int i = 1; i < split.length; i++) { |
| 26 | + String file = split[i]; |
| 27 | + String fileName = file.substring(0,file.indexOf("(")); |
| 28 | + //拆分字符串获取文件的内容 |
| 29 | + String fileContent = file.substring(file.indexOf("(")+1, file.lastIndexOf(")")); |
| 30 | + //获取文件的全部路径 |
| 31 | + String filePath = rootPath + fileName; |
| 32 | + if (map.containsKey(fileContent)){ |
| 33 | + List<String> list = map.get(fileContent); |
| 34 | + list.add(filePath); |
| 35 | + map.put(fileContent,list); |
| 36 | + }else { |
| 37 | + List<String> list = new ArrayList<>(); |
| 38 | + list.add(filePath); |
| 39 | + map.put(fileContent,list); |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + List<List<String>> result = new ArrayList<>(); |
| 44 | + for (Map.Entry<String,List<String>> entry : map.entrySet()){ |
| 45 | + if (entry.getValue().size()>1){ |
| 46 | + result.add(entry.getValue()); |
| 47 | + } |
| 48 | + } |
| 49 | + return result; |
| 50 | + } |
| 51 | +} |
0 commit comments