Leetcode 71 Simplify Path
The key of solving this problem is to use a stack. But before we do that we need to split the string based on /
. This way it will give us the parts between slashes which actually determines if we need to push of pop the stack.
'/a/..//b/./c/..../'
split ->
['a', '..', '', 'b', '.'. 'c', '....', '']
Note that we should ignore the empty string case here.
If we see ..
we should pop the stack as it indicates the parent folder so we should remove the previously pushed in elements from the stack.
If we see .
we don’t do anything.
Otherwise we push the element into the array.
At the end we just need to stick the elements in the stack together as the result.
Solution
/**
* @param {string} path
* @return {string}
*/
var simplifyPath = function(path) {
let stack = [];
let i = 0;
let split = path.split('/');
for(let i = 0; i < split.length; i++) {
let current = split[i]
if(current) {
if(current === '..') {
stack.pop();
} else if(current !== '.') {
stack.push(current);
}
}
}
if(!stack.length) {
return '/'
}
return stack.reduce((acc, x) => `${acc}/${x}`, '')
};
Time complexity is O(n)
. Space complexity is O(1)