609. 在系统中查找重复文件
https://leetcode-cn.com/problems/find-duplicate-file-in-system/
解法一:
建立map,以文件内容为key,路径集合为value。然后遍历map,路径集合长度大于1的文件即为重复。注意dict的key没有默认对应value(不像c++),因此遇到第一次出现的key时往往需要特殊处理。
class Solution:
def findDuplicate(self, paths: List[str]) -> List[List[str]]:
res = []
fileMap = {}
for path in paths:
strList = path.split(' ') #按空格切分
route = strList[0] #路径
for s in strList[1:]:
index = s.find('(')
file_name = s[ :index] #文件名
content = s[index+1 : -1] #内容
#若内容第一次出现在map,需要对路径集初始化
if content not in fileMap:
fileMap[content] = []
fileMap[content].append(route + '/' + file_name)
for f in fileMap:
if len(fileMap[f]) > 1:
res.append(fileMap[f])
return res
最后更新于