[LeetCode] 71. Simplify Path

Simplified path. Meaning of the questions is to give an absolute path in a Unix environment, simplify it. example,

Example 1:
Input: "/home/"
Output: "/home"
Explanation: Note that there is no trailing slash after the last directory name.

Example 2:
Input: "/../"
Output: "/"
Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.

Example 3:
Input: "/home//foo/"
Output: "/home/foo"
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.

Example 4:
Input: "/a/./b/../../c/"
Output: "/c"

Example 5:
Input: "/a/../../b/../c//.//"
Output: "/c"

Example 6:
Input: "/a//b////c/d//././/.."
Output: "/a/b/c"

Consider the case of invalid input does not need to be thinking of it is very simple, it will use stack stack. The idea is input by '/' into a small portion and then determines whether each part needs into the stack. (.); Otherwise it is normal points into the stack and an empty string ( '') to put encountered two points (..) not only hold but put part to eject before encountered. Then the final element of the stack together into an output string.

Time O (n)

Space O (n)

 1 /**
 2  * @param {string} path
 3  * @return {string}
 4  */
 5 var simplifyPath = function (path) {
 6     let stack = [];
 7     path = path.split('/');
 8     for (let i = 0; i < path.length; i++) {
 9         if (path[i] == '.' || path[i] == '') continue;
10         if (path[i] == '..') {
11             stack.pop();
12         } else {
13             stack.push(path[i]);
14         }
15     }
16     return '/' + stack.join('/');
17 };

 

Guess you like

Origin www.cnblogs.com/aaronliu1991/p/12302063.html