|
| 1 | +# 71. Simplify Path |
| 2 | +# 🟠 Medium |
| 3 | +# |
| 4 | +# https://leetcode.com/problems/simplify-path/ |
| 5 | +# |
| 6 | +# Tags: String - Stack |
| 7 | + |
| 8 | +import re |
| 9 | +import timeit |
| 10 | + |
| 11 | + |
| 12 | +# First merge contiguous directory separators into one, then split by |
| 13 | +# directory separators. Iterate over the resulting directories or ".." |
| 14 | +# elements, when we see "." we don't do anything, when we see a ".." we |
| 15 | +# "travel" one directory up by popping the last element on the stack, |
| 16 | +# anything else we consider a directory name and we push into the stack. |
| 17 | +# |
| 18 | +# Time complexity: O(n) - Cleaning and tokenizing the input needs to |
| 19 | +# visit each character of the input path. |
| 20 | +# Space complexity: O(n) - The stack can have as many characters as the |
| 21 | +# input. |
| 22 | +# |
| 23 | +# Runtime 35 ms Beats 58.39% |
| 24 | +# Memory 13.8 MB Beats 69.41% |
| 25 | +class Solution: |
| 26 | + def simplifyPath(self, path: str) -> str: |
| 27 | + # Step 1 combine multiple '////' into '/' |
| 28 | + clean = re.sub(r"/+", "/", path) |
| 29 | + # Step 2 split into directory names. |
| 30 | + # https://stackoverflow.com/a/34844548/2557030 |
| 31 | + tokens = [token for token in clean.split("/") if token] |
| 32 | + # Use a stack to store directory names |
| 33 | + stack = [] |
| 34 | + for token in tokens: |
| 35 | + if token == ".": |
| 36 | + continue |
| 37 | + if token == "..": |
| 38 | + if stack: |
| 39 | + stack.pop() |
| 40 | + continue |
| 41 | + stack.append(token) |
| 42 | + return "/" + "/".join(stack) |
| 43 | + |
| 44 | + |
| 45 | +def test(): |
| 46 | + executors = [Solution] |
| 47 | + tests = [ |
| 48 | + ["/../", "/"], |
| 49 | + ["/a/..", "/"], |
| 50 | + ["/a/../", "/"], |
| 51 | + ["/home/", "/home"], |
| 52 | + ["/abc/...", "/abc/..."], |
| 53 | + ["/a/./b/../../c/", "/c"], |
| 54 | + ["/a/../.././../../", "/"], |
| 55 | + ["/../../../../../a", "/a"], |
| 56 | + ["/home//foo/", "/home/foo"], |
| 57 | + ["/a//b//c//////d", "/a/b/c/d"], |
| 58 | + ["/a/./b/./c/./d/", "/a/b/c/d"], |
| 59 | + ] |
| 60 | + for executor in executors: |
| 61 | + start = timeit.default_timer() |
| 62 | + for _ in range(1): |
| 63 | + for col, t in enumerate(tests): |
| 64 | + sol = executor() |
| 65 | + result = sol.simplifyPath(t[0]) |
| 66 | + exp = t[1] |
| 67 | + assert result == exp, ( |
| 68 | + f"\033[93m» {result} <> {exp}\033[91m for" |
| 69 | + + f" test {col} using \033[1m{executor.__name__}" |
| 70 | + ) |
| 71 | + stop = timeit.default_timer() |
| 72 | + used = str(round(stop - start, 5)) |
| 73 | + cols = "{0:20}{1:10}{2:10}" |
| 74 | + res = cols.format(executor.__name__, used, "seconds") |
| 75 | + print(f"\033[92m» {res}\033[0m") |
| 76 | + |
| 77 | + |
| 78 | +test() |
0 commit comments