Created
May 18, 2021 16:42
-
-
Save vrat28/8afb4c28494c31b9a28a7cb3d3ab1bb7 to your computer and use it in GitHub Desktop.
Find duplicate Files in file system(Swift)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
func findDuplicate(_ paths: [String]) -> [[String]] { | |
var map = [String:[String]]() | |
for path in paths { | |
var dir = "" | |
let components = path.split(separator : " ") | |
if components.count > 1 { dir = String(components[0])} | |
for i in 1..<components.count { | |
if let fileNamePair = getFileNameContentPair(String(components[i])){ | |
let key = fileNamePair.0 | |
let value = "\(dir)/\(fileNamePair.1)" | |
if let existing = map[key] { | |
map[key] = existing + [value] | |
} | |
else{ | |
map[key] = [value] | |
} | |
} | |
} | |
} | |
return map.values.filter{ $0.count > 1} | |
} | |
// filename(content) | |
func getFileNameContentPair(_ path:String) -> (String,String)?{ | |
if let firstIdx = path.indexInt(of:"("), let lastIdx = path.indexInt(of:")") { | |
let fileName = String(path.prefix(firstIdx)) | |
let startIdx = path.index(path.startIndex, offsetBy: firstIdx - 1) | |
let last = path.index(path.startIndex, offsetBy: lastIdx) | |
let content = String(path[startIdx..<last]) | |
return (content,fileName) | |
} | |
return nil | |
} | |
} | |
public extension String { | |
func indexInt(of char: Character) -> Int? { | |
return firstIndex(of: char)?.utf16Offset(in: self) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment