-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimplifyPath.js
More file actions
54 lines (45 loc) · 1.51 KB
/
Copy pathsimplifyPath.js
File metadata and controls
54 lines (45 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
Given a string path, which is an absolute path (starting with a slash '/') to a file or directory in
a Unix-style file system, convert it to the simplified canonical path.
In a Unix-style file system, a period '.' refers to the current directory, a double period '..' refers
to the directory up a level, and any multiple consecutive slashes (i.e. '//') are treated as a single slash '/'.
The canonical path should have the following format:
- Begins with a single slash '/'.
- Directories separated by a single slash '/'.
- Not end with trailing '/'.
- Only contains the directories on the path (no '.' or '..').
Example 1:
Input: path = "/home/"
Output: "/home"
Example 2:
Input: path = "/../"
Output: "/"
Example 3:
Input: path = "/home//foo/"
Output: "/home/foo"
Constraints:
1 <= path.length <= 3000
path consists of English letters, digits, period '.', slash '/' or '_'.
path is a valid absolute Unix path.
*/
/**
* @param {string} path
* @return {string}
*/
function simplifyPath(path) {
const parts = path.split('/');
const stack = [];
for (const part of parts) {
if (part === '' || part === '.') continue;
if (part === '..') {
if (stack.length > 0) stack.pop();
} else {
stack.push(part);
}
}
return '/' + stack.join('/');
}
// Example usage:
console.log(simplifyPath("/home/")); // Output: "/home"
console.log(simplifyPath("/../")); // Output: "/"
console.log(simplifyPath("/home//foo/")); // Output: "/home/foo"