|
| 1 | + |
1 | 2 | /**
|
2 | 3 | * Stack
|
3 |
| - * https://leetcode.com/problems/simplify-path/ |
4 |
| - * |
5 |
| - * Time O(n) | Space O(n) |
| 4 | + * Time O(N) | Space O(N) |
| 5 | + * https://leetcode.com/problems/simplify-path |
6 | 6 | *@param {string} path
|
7 | 7 | *@return {string}
|
8 | 8 | */
|
9 |
| -varsimplifyPath=function(path){ |
10 |
| -letcurrunt=''; |
11 |
| -letmyStack=[]; |
12 |
| -path=`/${path}/`; |
13 |
| -for(leti=0;i<path.length;i++){ |
14 |
| - |
15 |
| -if(path[i]==='/'){ |
16 |
| -if(currunt=='..'){ |
17 |
| -myStack.pop(); |
18 |
| -}elseif(currunt!==''&&currunt!=='.'){ |
19 |
| -myStack.push(currunt); |
20 |
| -} |
21 |
| -currunt=''; |
22 |
| -}else{ |
23 |
| -currunt+=path[i]; |
24 |
| -} |
25 |
| - |
26 |
| -} |
27 |
| - |
28 |
| -myStack=myStack.join('/'); |
29 |
| -myStack='/'+myStack; |
30 |
| -returnmyStack; |
| 9 | +varsimplifyPath=(path,slash='/',stack=[])=>{ |
| 10 | +constpaths=path.split(slash).filter(Boolean); |
| 11 | + |
| 12 | +for(const_pathofpaths)traversePath(_path,stack); |
| 13 | + |
| 14 | +return`${slash}${stack.join(slash)}`; |
| 15 | +}; |
| 16 | + |
| 17 | +consttraversePath=(path,stack)=>{ |
| 18 | +if(canPush(path))returnstack.push(path); |
| 19 | + |
| 20 | +if(canPop(path,stack))stack.pop(); |
31 | 21 | };
|
| 22 | + |
| 23 | +constcanPush=(path)=>!( |
| 24 | +isCurrentDirectory(path)|| |
| 25 | +isParentDirectory(path) |
| 26 | +); |
| 27 | + |
| 28 | +constcanPop=(path,stack)=> |
| 29 | +isParentDirectory(path)&& |
| 30 | +!isEmpty(stack); |
| 31 | + |
| 32 | +constisCurrentDirectory=(path)=>(path==='.'); |
| 33 | + |
| 34 | +constisParentDirectory=(path)=>(path==='..'); |
| 35 | + |
| 36 | +constisEmpty=({ length})=>(0===length); |