Skip to content

Commit 9905b94

Browse files
Create Simplify Path.md
1 parent f824fd3 commit 9905b94

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

JS-Algo/Simplify Path.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#### 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.
2+
3+
#### 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 '/'. For this problem, any other format of periods such as '...' are treated as file/directory names.
4+
5+
#### The canonical path should have the following format:
6+
7+
- The path starts with a single slash '/'.
8+
- Any two directories are separated by a single slash '/'.
9+
- The path does not end with a trailing '/'.
10+
- The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period '.' or double period '..')
11+
- Return the simplified canonical path.
12+
13+
14+
15+
<img width="477" alt="Screen Shot 2021-11-09 at 22 18 17" src="https://user-images.githubusercontent.com/37787994/141054383-143f100b-8f65-42ac-878a-e30589bb4564.png">
16+
<img width="477" alt="Screen Shot 2021-11-09 at 22 18 30" src="https://user-images.githubusercontent.com/37787994/141054401-3b73159d-23a7-4d6f-a89c-facfbc393d44.png">
17+
18+
19+
20+
```JS
21+
/**
22+
* @param {string} path
23+
* @return {string}
24+
*/
25+
var simplifyPath = function(path) {
26+
let stack = [];
27+
path = path.split('/');
28+
29+
for(let i = 0; i < path.length; i++) {
30+
if(path[i] === '.' || path[i] === '') continue;
31+
if(path[i] === '..') stack.pop();
32+
else stack.push(path[i]);
33+
}
34+
// add a '/' between each stack block
35+
// stack [home -> foo] home/foo
36+
return '/' + stack.join('/')
37+
};
38+
```

0 commit comments

Comments
 (0)