-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathNo71.simplify-path.js
44 lines (40 loc) · 990 Bytes
/
No71.simplify-path.js
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
/**
* Difficulty:
* Medium
*
* Desc:
* Given an absolute path for a file (Unix-style), simplify it.
*
* Example:
* path = "/home/", => "/home"
* path = "/a/./b/../../c/", => "/c"
*
* Note:
* 1. Did you consider the case where path = "/../"?
* In this case, you should return "/".
* 2. Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
* In this case, you should ignore redundant slashes and return "/home/foo".
*
* 简化类似 Unix 下的路径。注意处理类似 '/../' 或者 '/home//ecmadao' 的情况
*/
/**
* 思路:
* 逐步深入的 folder 栈
*/
/**
* @param {string} path
* @return {string}
*/
var simplifyPath = function(path) {
const folders = []
const pathes = path.split('/')
for (const p of pathes) {
if (p === '.' || p === '') continue
if (p === '..') {
folders.length && folders.pop()
} else {
folders.push(p)
}
}
return '/' + folders.join('/')
}