Skip to content

Commit cf13469

Browse files
authored
Merge pull request #2614 from aadil42/patch-60
2 parents 6e9bbd9 + f65d073 commit cf13469

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

javascript/0071-simplify-path.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
2+
/**
3+
* Stack
4+
* Time O(N) | Space O(N)
5+
* https://leetcode.com/problems/simplify-path
6+
* @param {string} path
7+
* @return {string}
8+
*/
9+
var simplifyPath = (path, slash = '/', stack = []) => {
10+
const paths = path.split(slash).filter(Boolean);
11+
12+
for (const _path of paths) traversePath(_path, stack);
13+
14+
return `${slash}${stack.join(slash)}`;
15+
};
16+
17+
const traversePath = (path, stack) => {
18+
if (canPush(path)) return stack.push(path);
19+
20+
if (canPop(path, stack)) stack.pop();
21+
};
22+
23+
const canPush = (path) => !(
24+
isCurrentDirectory(path) ||
25+
isParentDirectory(path)
26+
);
27+
28+
const canPop = (path, stack) =>
29+
isParentDirectory(path) &&
30+
!isEmpty(stack);
31+
32+
const isCurrentDirectory = (path) => (path === '.');
33+
34+
const isParentDirectory = (path) => (path === '..');
35+
36+
const isEmpty = ({ length }) => (0 === length);

0 commit comments

Comments
 (0)