码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 71. Simplify Path

时间:2020-02-13 09:21:36      阅读:51      评论:0      收藏:0      [点我收藏+]

标签:after   imp   root   需要   cto   ==   @param   字符   dir   

简化路径。题意是给一个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 };

 

[LeetCode] 71. Simplify Path

标签:after   imp   root   需要   cto   ==   @param   字符   dir   

原文地址:https://www.cnblogs.com/aaronliu1991/p/12302063.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!