[LeetCode] 71. Simplify Path

简化路径。题意是给一个Unix环境下的绝对路径,请简化之。例子,

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"

不需要考虑input是invalid的情况所以思路很简单,会用到stack栈。思路是将input按 '/' 分成一个个小的部分,然后判断每个部分是否需要放进栈。遇到点(.)和空的字符串(' ')就放,遇到两个点(..)不仅不放反而要弹出之前放的部分;其他情况就正常放进栈。最后再将栈内的元素拼接成字符串输出。

时间O(n)

空间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 };

猜你喜欢

转载自www.cnblogs.com/aaronliu1991/p/12302063.html