题目描述
Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.
In a UNIX-style file system, a period .
refers to the current directory. Furthermore, a double period ..
moves the directory up a level. For more information, see: Absolute path vs relative path in Linux/Unix
Note that the returned canonical path must always begin with a slash /
, and there must be only a single slash /
between two directory names. The last directory name (if it exists) must not end with a trailing /
. Also, the canonical path must be the shortest string representing the absolute path.
Example 1:
1 | Input: "/home/" |
Example 2:
1 | Input: "/../" |
Example 3:
1 | Input: "/home//foo/" |
Example 4:
1 | Input: "/a/./b/../../c/" |
Example 5:
1 | Input: "/a/../../b/../c//.//" |
Example 6:
1 | Input: "/a//b////c/d//././/.." |
# 解法1
思路:一次取出path中不等于//的部分(表示的是目录),若该部分是..,表示返回上级目录,若此时不在根目录下则有上级目录可以返回,则返回上级目录,即删除当前的目录。若该部分是.,表示当前目录,则什么也不做。否则,将新的目录加入到当前路径中(这里用vector来存储当前路径中的所有目录名)。最后将整个目录用/连接起来。另外,这里的根目录是隐含的,没有在初始化路径时加入到vector中,这是因为我们知道当前路径中的第一个目录一定是根目录。
注意:vector等的size()都是无符号数,无符号数都大于等于0,无符号数与有符号数做减法时不会产生负数,而是会变成一个很大的整数。参见:c++数据类型基础知识
AC代码:
1 | class Solution { |
复杂度分析
时间复杂度为为O(n),只从左到右扫描了整个路径字符串一遍。
空间复杂度为O(n),使用了一个vector来存储路径。