Skip to content

Commit 54ffb54

Browse files
committed
finish 71
1 parent 3fbd84c commit 54ffb54

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

71. Simplify Path.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* 71. Simplify Path
3+
*
4+
* Given an absolute path for a file (Unix-style), simplify it.
5+
*
6+
* For example,
7+
* path = "/home/", => "/home"
8+
* path = "/a/./b/../../c/", => "/c"
9+
*
10+
* Corner Cases:
11+
*
12+
* Did you consider the case where path = "/../"?
13+
* In this case, you should return "/".
14+
* Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
15+
* In this case, you should ignore redundant slashes and return "/home/foo".
16+
*/
17+
18+
/**
19+
* @param {string} path
20+
* @return {string}
21+
*/
22+
var simplifyPath = function(path) {
23+
var arr = path.split('/');
24+
var stack = [];
25+
var len = arr.length;
26+
var item = '';
27+
for (var i = 0; i < len; i++) {
28+
item = arr[i];
29+
if (item === '' || item === '.') continue;
30+
if (item === '..') {
31+
stack.pop();
32+
} else {
33+
stack.push(item);
34+
}
35+
}
36+
return '/' + stack.join('/');
37+
};
38+
39+
// 栈

0 commit comments

Comments
 (0)