forked from ecmadao/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNo71.simplify-path.js
More file actions
57 lines (52 loc) · 1.42 KB
/
No71.simplify-path.js
File metadata and controls
57 lines (52 loc) · 1.42 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
55
56
57
/**
* 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' 的情况
*/
/**
* 思路:
* 构建一个树的结构,每个节点保留其当前目录名称和父节点
* 遍历输入的路径,获取到最后的结果节点,然后向上遍历,最后得到合法的最简洁的路径
*/
var Node = function(folder, father) {
this.folder = folder;
this.father = father;
};
/**
* @param {string} path
* @return {string}
*/
var simplifyPath = function(path) {
var node = new Node('', null);
var paths = path.split('/');
for (var i = 0; i < paths.length; i += 1) {
var p = paths[i];
if (!p || p === '.') continue;
if (p === '..') {
if (!node.father) continue;
node = node.father;
} else {
node = new Node(p, node);
}
}
var result = '';
while(node.father) {
result = result ? node.folder + '/' + result : node.folder;
node = node.father;
}
return '/' + result;
};