/71. Simplify Path

71. Simplify Path

Medium
Strings50.2% acceptance

Given a string representing an absolute Unix-style file system path, return its simplified canonical form. The input path always starts with /. The simplification rules are: (1) . means current directory and should be ignored; (2) .. means parent directory and should remove the previous directory from the path, unless at root; (3) multiple consecutive slashes are treated as a single slash; (4) sequences of periods not equal to . or .. are treated as valid directory names; (5) the output must start with a single slash, not end with a slash unless it is root, and not contain . or ...

Example 1

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

Output: /_/b/c

Explanation: The _ is a valid directory name. .. removes a. . is ignored. Trailing slash is removed.

Example 2

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

Output: //a/c/d

Explanation: Multiple slashes are treated as single. .. removes b. . is ignored.

Example 3

Input: /.hidden/../visible/

Output: //visible

Explanation: .hidden is a valid directory name, .. removes it. Trailing slash removed.

Constraints

  • 1 <= len(absolute_path) <= 3000
  • absolute_path consists of English letters, digits, ., /, and _
  • absolute_path is a valid absolute Unix path
Python (current runtime)

Case 1

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

Expected: '//foo/baz/qux'

Case 2

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

Expected: '//c'

Case 3

Input: '/.config/../data/../logs/'

Expected: '//logs'

Case 4

Input: '//../'

Expected: '/'

Case 5

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

Expected: '//a/.../c'