LeetCode 刷题记录 71. Simplify Path

题目:
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:

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//bc/d//././/…”
Output: “/a/b/c”

绝对路径和相对路径的区别
ABSOLUTE PATH VS RELATIVE PATH IN LINUX/UNIX

Example 4: My present location is /etc/lvm and I want to change my location to /opt/oradba

Using relative path:

cd …/…/opt/oradba

解法:
首先我们将目标字符串按照"/“来分割
由于字符串第一个字符为”/",所以会切割出来一个空字符串""
然后依次进行处理,如果是空字符串或者是".",代表当前目录,我们直接可以忽略不管
如果是"…",代表是父亲目录,我们直接去除我们上一个加入的目录,此时我们要注意如果此时没有目录添加进来,我们是不能去除上一层目录,我们可以使用出栈操作,
在c++中可以使用vector中的pop_back()操作,在java中可以使用LinkedList的removeLast来去除最后一个元素
剩下的情况,我们直接添加目录即可,但是我们要判断此时的字符串不是"…",如果字符串为"…“而目录不为空,直接我们在之前的if条件中已经判断过了,但是目录为空的条件下,如果我们不加判断字符串不是”…“会将”…"错误的加入到目录中去。

如:"/a/./b/…/…/c/"
分割的第一个为空字符串忽略
分割的第二个为a,加入列表a
分割的第三个为. 忽略
分割的第四个为b,加入列表a,b
分割的第四个为…, 这代表父亲目录,即当前目录为b,b的父亲目录为a,所以我们要去除b目录,列表a
分割的第五个为…, 这代表父亲目录,即当前目录为a,b的父亲目录为根目录,所以我们要去除a目录,列表为空、
分割的第六个为c,加入列表为c

然后我们将列表中的元素用"/“连接起来,注意我们要在最前面加上”/"
c++:
c++中没有连接函数,我们只有遍历列表,然后在每个元素前加上"/",最后如果列表为空,我们直接输出"/"就可以了
c++中用stringstream类来实现分割功能,getline(ss,t,’/’)函数最后一个参数是字符

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值