Created
October 21, 2019 23:14
-
-
Save OmarKRostom/85744833b9fb8d75013e3c32a0b8f91f to your computer and use it in GitHub Desktop.
Solution to removing subfolders from folder (https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/submissions/)
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
public static List<String> removeSubfolders(String[] folders) { | |
HashSet<String> rootFoldersOnly = new HashSet<>(); | |
HashSet<String> setFolders = new HashSet<>(Arrays.asList(folders)); | |
for (String folder: folders) { | |
int searchIndex = 0; | |
int currentSegmentIndex = 1; | |
String matchingDirectory = ""; | |
String[] segments = folder.split("/"); | |
while(currentSegmentIndex < segments.length) { | |
searchIndex += segments[currentSegmentIndex].length() + 1; | |
String segment = folder.substring(0, searchIndex); | |
matchingDirectory = segment; | |
if (setFolders.contains(matchingDirectory.toString())) { | |
rootFoldersOnly.add(segment); | |
break; | |
} | |
currentSegmentIndex++; | |
} | |
} | |
return new ArrayList<>(rootFoldersOnly); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment