/71. Simplify Unix File Path

71. Simplify Unix File Path

Medium
Strings50.2% acceptance

Given a string representing an absolute Unix-style file path, return its simplified canonical form. The input path always starts with a slash (/). The simplification rules are: (1) A single period (.) means current directory and should be ignored; (2) A double period (..) means parent directory and removes the previous directory from the path, unless at root; (3) Multiple consecutive slashes are treated as a single slash; (4) Any sequence of periods not matching . or .. is treated as a valid directory name; (5) The output must start with a single slash, directories separated by one slash, no trailing slash unless root, and no . or .. in the result.

Example 1

Input: /a/b/../c/./d/

Output: /a/c/d

Explanation: .. removes b, . is ignored, trailing slash removed.

Example 2

Input: /foo/bar//baz/../qux/..

Output: /foo/bar

Explanation: Multiple slashes are reduced, .. removes baz and then qux.

Example 3

Input: /x/./y/../z/...

Output: /x/z/...

Explanation: . ignored, .. removes y, ... is a valid directory name.

Constraints

  • 1 <= len(file_path) <= 3000
  • file_path consists of English letters, digits, period ., slash /, or underscore _
  • file_path is a valid absolute Unix path
Python (current runtime)

Case 1

Input: '/_/a/../b/./c/'

Expected: '/_/b/c'

Case 2

Input: '////a/b/c/..///d/../e/'

Expected: '//a/b/e'

Case 3

Input: '/.hidden/../visible/./../'

Expected: '/'

Case 4

Input: '//dir1//dir2/../dir3/..///'

Expected: '//dir1'

Case 5

Input: '///a/..///..///..///'

Expected: '/'