Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 8bc6588

Browse files
Simplify Path
1 parent b37adb0 commit 8bc6588

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

LeetcodeProblems/Simplify_Path.js

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/*
2+
Simplify Path
3+
4+
https://leetcode.com/problems/simplify-path/description/
5+
6+
Given an absolute path for a file (Unix-style), simplify it.
7+
8+
For example,
9+
path = "/home/", => "/home"
10+
path = "/a/./b/../../c/", => "/c"
11+
path = "/a/../../b/../c//.//", => "/c"
12+
path = "/a//b////c/d//././/..", => "/a/b/c"
13+
14+
In a UNIX-style file system, a period ('.') refers to the current directory, so it can be ignored in a simplified path. Additionally, a double period ("..") moves up a directory, so it cancels out whatever the last directory was. For more information, look here: https://en.wikipedia.org/wiki/Path_(computing)#Unix_style
15+
16+
Corner Cases:
17+
18+
Did you consider the case where path = "/../"?
19+
In this case, you should return "/".
20+
Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
21+
In this case, you should ignore redundant slashes and return "/home/foo".
22+
*/
23+
24+
var simplifyPath = function(path) {
25+
var queue = [];
26+
var iter = path.length - 1;
27+
while(iter >= 0) {
28+
if(path.charAt(iter) === "/") {
29+
iter--;
30+
} else if(path.slice(iter - 1, iter + 1) == "/.") {
31+
iter -= 2;
32+
} else if(path.slice(iter - 2, iter + 1) === "/..") {
33+
iter -= 3;
34+
queue.unshift("/..");
35+
} else { // it's a characteriter
36+
const endChars = iter;
37+
while(iter >= 0 && path.charAt(iter) !== "/") {
38+
iter--;
39+
}
40+
if(queue.length > 0 && queue[0] === "/..") {
41+
queue.shift();
42+
} else {
43+
queue.push("/" + path.slice(iter + 1, endChars + 1));
44+
}
45+
}
46+
}
47+
var ret = "";
48+
49+
while(queue.length > 0) {
50+
elem = queue.shift();
51+
if(elem == "/..") {
52+
while(queue.length > 0 && queue.shift == "/..") {
53+
elem += "/..";
54+
}
55+
elem = (queue.length > 0) ? elem : "";
56+
} else {
57+
ret = elem + ret;
58+
}
59+
}
60+
return (ret.length == 0) ? "/" : ret;
61+
};
62+
63+
var main = function(){
64+
console.log(simplifyPath("/../c"));
65+
console.log(simplifyPath("/.."));
66+
console.log(simplifyPath("/home/")); // => "/home"
67+
console.log(simplifyPath("/a/./b/../../c/")); // => "/c"
68+
console.log(simplifyPath("/a/../../b/../c//.//")); // => "/c"
69+
console.log(simplifyPath("/a//b////c/d//././/..")) // => "/a/b/c"
70+
}
71+
72+
module.exports.main = main

0 commit comments

Comments
 (0)