Simplify Path
Given an absolute path for a file system, which starts with a slash '/', simplify it. The file system uses a double slash '//' as a single slash and a single dot '.' as the current directory. A double dot '..' moves up one directory level. This challenge is crucial for understanding how to process and normalize file paths, a common task in operating systems and file management applications.
Problem Description
The goal is to take a given absolute path string and return its simplified, canonical form.
Key Requirements:
- The simplified path should always start with a single slash '/'.
- Directory names in the path are separated by a single slash.
- Avoid redundant slashes: multiple consecutive slashes should be replaced by a single slash.
- Handle the current directory: a single dot '.' should be ignored.
- Handle moving up a directory: a double dot '..' should move up one level in the directory hierarchy. If '..' is encountered at the root level, it should remain at the root.
- The simplified path should not end with a trailing slash, unless it is the root directory itself ("/") .
Expected Behavior:
///a/./b/../../c/should become/c./home/should become/home./../should become/.
Edge Cases:
- Empty path string.
- Path with only slashes (e.g.,
//). - Path with only dots and slashes (e.g.,
./../). - Path that attempts to go above the root directory.
Examples
Example 1:
Input: "/home/"
Output: "/home"
Explanation: The trailing slash is removed.
Example 2:
Input: "/../"
Output: "/"
Explanation: Moving up from the root directory remains at the root.
Example 3:
Input: "/home//foo/"
Output: "/home/foo"
Explanation: Multiple slashes are reduced to a single slash, and the trailing slash is removed.
Example 4:
Input: "/a/./b/../../c/"
Output: "/c"
Explanation:
- `/a` -> current directory is 'a'
- `./` -> current directory is still 'a'
- `b/` -> current directory is 'a/b'
- `../` -> move up from 'a/b' to 'a'
- `../` -> move up from 'a' to '/' (root)
- `c/` -> current directory is 'c'
The final path is `/c`.
Constraints
1 <= path.length <= 300pathcontains only English letters, digits, '.', '/', or '_'.pathis a valid absolute Unix-style path.
Notes
Consider using a stack-like data structure to keep track of directory names as you process the path components. This will make handling the '..' operation more straightforward. Remember to handle the initial slash and potential empty components resulting from multiple slashes.