Given an absolute path for a file (Unix-style), simplify it.
For example, path = "/home/"
, =>
"/home"
path =
"/a/./b/../../c/"
, => "/c"
Corner Cases:
"/../"
? In this case, you should return "/"
.
'/'
together, such as "/home//foo/"
. In this
case, you should ignore redundant slashes and return
"/home/foo"
.
Use stack to handle /../
.
RegExp matching.
/**
* @param {string} path
* @return {string}
*/
var simplifyPath = function(path) {
return '/' + (path.match(/[^\/]+/g) || [])
.reduce((stack, p) => {
if (p === '..') {
stack.pop()
} else if (p !== '.') {
stack.push(p)
}
return stack
}, [])
.join('/')
};
Direct search.
/**
* @param {string} path
* @return {string}
*/
var simplifyPath = function(path) {
const len = path.length
const stack = []
let e = 0
while (e < len) {
while (e < len && path[e] === '/') {
e++
}
const s = e
while (e < len && path[e] !== '/') {
e++
}
if (s < e) {
const p = path.slice(s, e)
if (p === '..') {
stack.pop()
} else if (p !== '.') {
stack.push(p)
}
}
}
return '/' + stack.join('/')
};
Template generated via Leetmark.