|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# 1233. Remove Sub-Folders from the Filesystem |
| 4 | +# Medium |
| 5 | +# https://leetcode.com/problems/remove-sub-folders-from-the-filesystem |
| 6 | + |
| 7 | +=begin |
| 8 | +Given a list of folders folder, return the folders after removing all sub-folders in those folders. You may return the answer in any order. |
| 9 | +If a folder[i] is located within another folder[j], it is called a sub-folder of it. A sub-folder of folder[j] must start with folder[j], followed by a "/". For example, "/a/b" is a sub-folder of "/a", but "/b" is not a sub-folder of "/a/b/c". |
| 10 | +The format of a path is one or more concatenated strings of the form: '/' followed by one or more lowercase English letters. |
| 11 | +For example, "/leetcode" and "/leetcode/problems" are valid paths while an empty string and "/" are not. |
| 12 | +
|
| 13 | +Example 1: |
| 14 | +Input: folder = ["/a","/a/b","/c/d","/c/d/e","/c/f"] |
| 15 | +Output: ["/a","/c/d","/c/f"] |
| 16 | +Explanation: Folders "/a/b" is a subfolder of "/a" and "/c/d/e" is inside of folder "/c/d" in our filesystem. |
| 17 | +
|
| 18 | +Example 2: |
| 19 | +Input: folder = ["/a","/a/b/c","/a/b/d"] |
| 20 | +Output: ["/a"] |
| 21 | +Explanation: Folders "/a/b/c" and "/a/b/d" will be removed because they are subfolders of "/a". |
| 22 | +
|
| 23 | +Example 3: |
| 24 | +Input: folder = ["/a/b/c","/a/b/ca","/a/b/d"] |
| 25 | +Output: ["/a/b/c","/a/b/ca","/a/b/d"] |
| 26 | +
|
| 27 | +Constraints: |
| 28 | +* 1 <= folder.length <= 4 * 104 |
| 29 | +* 2 <= folder[i].length <= 100 |
| 30 | +* folder[i] contains only lowercase letters and '/'. |
| 31 | +* folder[i] always starts with the character '/'. |
| 32 | +* Each folder name is unique. |
| 33 | +=end |
| 34 | + |
| 35 | +# @param {String[]} folder |
| 36 | +# @return {String[]} |
| 37 | +def remove_subfolders(folder) |
| 38 | + folder.sort! |
| 39 | + |
| 40 | + ans = [folder[0]] |
| 41 | + |
| 42 | + (1...folder.length).each do |i| |
| 43 | + last_folder = ans[-1] + "/" |
| 44 | + |
| 45 | + if !folder[i].start_with?(last_folder) |
| 46 | + ans << folder[i] |
| 47 | + end |
| 48 | + end |
| 49 | + |
| 50 | + ans |
| 51 | +end |
| 52 | + |
| 53 | +# **************** # |
| 54 | +# TEST # |
| 55 | +# **************** # |
| 56 | + |
| 57 | +require "test/unit" |
| 58 | +class Test_remove_subfolders < Test::Unit::TestCase |
| 59 | + def test_ |
| 60 | + assert_equal ["/a", "/c/d", "/c/f"], remove_subfolders(["/a", "/a/b", "/c/d", "/c/d/e", "/c/f"]) |
| 61 | + assert_equal ["/a"], remove_subfolders(["/a", "/a/b/c", "/a/b/d"]) |
| 62 | + assert_equal ["/a/b/c", "/a/b/ca", "/a/b/d"], remove_subfolders(["/a/b/c", "/a/b/ca", "/a/b/d"]) |
| 63 | + end |
| 64 | +end |
0 commit comments