작심삼일

[LeetCode] 609 | Find Duplicate File in System | Python 본문

스터디/코테

[LeetCode] 609 | Find Duplicate File in System | Python

yun_s 2022. 9. 19. 10:06
728x90
반응형

문제 링크: https://leetcode.com/problems/find-duplicate-file-in-system/


문제

Given a list paths of directory info, including the directory path, and all the files with contents in this directory, return all the duplicate files in the file system in terms of their paths. You may return the answer in any order.

A group of duplicate files consists of at least two files that have 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 the 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 groups 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"

조건

  • 1 <= paths.length <= $2 * 10^4$
  • 1 <= paths[i].length <= 3000
  • 1 <= sum(paths[i].length) <= $5 * 10^5$
  • paths[i] consist of English letters, digits, '/', '.', '(', ')', and ' '.
  • You may assume no files or directories share the same name in the same directory.
  • You may assume each given directory info represents a unique directory. A single blank space separates the directory path and file info.

내 풀이

paths에 있는 path 안에 있는 파일별로 파일 이름과 txt안의 내용들로 나눈다.

txt안의 내용들을 key로, path+파일 이름을 value로 해서 dictionary에 저장한다.

중복된 파일들만 출력해야하므로 dictionary의 value의 값이 하나 이상인 것(txt의 내용이 여러 파일에서 같은 것)만 ans에 따로 모아 리턴한다.


코드

class Solution:
    def findDuplicate(self, paths: List[str]) -> List[List[str]]:
        directories = defaultdict(list)
        ans = []
        
        for path in paths:
            path = path.split(' ')
            root = path[0]
            
            for file in path[1:]:
                name, txt = file[:-1].split('(')
                directories[txt].append(root+'/'+name)
        
        for value in directories.values():
            if len(value) > 1:
                ans.append(value)
                
        return ans
728x90
반응형
Comments