Show problems as
Classic problem #71MediumStringStack

Simplify Path

Real-world version: Canonical Store Locator
Tracked in this browser only
Read Simplify Path on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstExpression Evaluation · Stacks & Queues, animated step by step

An artifact store addresses every folder with a locator that begins at the root, written as /. A locator is a run of pieces separated by /, and the store reads it like this:

  • a piece of . means stay where you are;
  • a piece of .. means step back to the folder that contains the current one, and at the root it does nothing at all;
  • any other piece is a folder name, and names may contain letters, digits, underscores and even runs of dots such as ..., which are ordinary names and not steps;
  • separators may be doubled up, and // behaves exactly like /.

The canonical form of a locator starts with /, puts exactly one / between consecutive folder names, and never ends with / unless it is the root by itself. Given path, return its canonical form.

Examples

Example 1

Input
path = "/store//alpha/"
Output
"/store/alpha"

The doubled separator collapses to one and the trailing separator is dropped, leaving the two folder names in place.

Example 2

Input
path = "/a/./b/../../c/"
Output
"/c"

`.` leaves the position alone, the first `..` undoes `b` and the second undoes `a`, so only `c` is left below the root.

Example 3

Input
path = "/_x/y/.._/.."
Output
"/_x/y"

`.._` is an ordinary folder name, so it is entered like any other, and the final `..` steps back out of it.

Example 4

Input
path = "/..."
Output
"/..."

A piece of three dots is a folder name, so the canonical form keeps it.

Constraints

  • 1 <= path.length <= 3000
  • path holds English letters, digits, '.', '/' and '_' only.
  • path is a valid absolute locator, so it starts with '/'.

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def simplify_path(path: str) -> str:
Java
public String simplifyPath(String path)