LeetCode 609: Find Duplicate File in System(python)

来源:互联网 发布:淘宝有哪些女装潮店 编辑:程序博客网 时间:2024/06/05 00:10

原题:
Given a list of directory info including directory path, and all the files with contents in this directory, you need to find out all the groups of duplicate files in the file system in terms of their paths.
A group of duplicate files consists of at least two files that have exactly the same content.

A single directory info string in the input list has the following format:
“root/d1/d2/…/dm f1.txt(f1_content) f2.txt(f2_content) … fn.txt(fn_content)”

It means there are n files (f1.txt, f2.txt … fn.txt with content f1_content, f2_content … fn_content, respectively) in directory root/d1/d2/…/dm. Note that n >= 1 and m >= 0. If m = 0, it means the directory is just the root directory.

The output is a list of group of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format:”directory_path/file_name.txt”

Example 1:
Input:
[“root/a 1.txt(abcd) 2.txt(efgh)”, “root/c 3.txt(abcd)”, “root/c/d 4.txt(efgh)”, “root 4.txt(efgh)”]
Output:
[[“root/a/2.txt”,”root/c/d/4.txt”,”root/4.txt”],[“root/a/1.txt”,”root/c/3.txt”]]

Note:
No order is required for the final output.
You may assume the directory name, file name and file content only has letters and digits, and the length of file content is in the range of [1,50].
The number of files given is in the range of [1,20000].
You may assume no files or directories share the same name in a same directory.
You may assume each given directory info represents a unique directory. Directory path and file infos are separated by a single blank space.

思路:
题目看着有点长,其实主要意思就一句话:查找并输出内容相同的文件的目录。比如:[“root/a 1.txt(abcd) 2.txt(efgh)”, “root/c 3.txt(abcd)”, “root/c/d 4.txt(efgh)”, “root 4.txt(efgh)”],内容为efgh的文件有三个,内容为abcd的文件有两个,所以efgh和abcd均为重复文件,结果就是输出重复文件的目录。我们要做的工作可以分为三步:一、通过字符串操作把所有的文件目录和内容按照标准的格式一一对应分割好,存为path和content; 二、把一一对应的数据存入字典dict中,content为主键,content相同的path全部存放在content为主键对应的list中;三、找到重复文件(len(dict[content])>1),并输出结果。

代码:

class Solution:    def findDuplicate(self, paths):        """        :type paths: List[str]        :rtype: List[List[str]]        """        dict1={}        for i in range(0,len(paths)):            list1=[]            list1=paths[i].split(" ")            rootpath=list1[0]            for j in range(1,len(list1)):                list2=[]                list2=list1[j].split("(")                subpath=list2[0]                content=list2[1].split(")")[0]                path=rootpath+"/"+subpath                if content not in dict1:                    dict1[content]=[]                dict1[content].append(path)        rList=[]        valuesList=[]        valuesList=list(dict1.values())        #Find and Save Duplicate File        for i in range(0,len(valuesList)):            if(len(valuesList[i])>1):                rList.append(valuesList[i])        return  rList