71. 简化路径(python)

题目描述(中等)

给定一个文档 (Unix-style) 的完全路径,请进行路径简化。

例如,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

边界情况:

  • 你是否考虑了 路径 = "/../" 的情况?
    在这种情况下,你需返回 "/" 。
  • 此外,路径中也可能包含多个斜杠 '/' ,如 "/home//foo/" 。
    在这种情况下,你可忽略多余的斜杠,返回 "/home/foo" 。

思路分析

把几种边界情况考虑清楚即可:

  1. 如果是‘.’,则自动去除
  2. 如果是‘..’,则把前一个有效字符去除
  3. 如果是多个连续斜杠‘/’,则去除这些斜杠“/”

根据这几个限定,编码实现都是先通过‘/’将有效字符分割出来,接下来可以采用两种风格编码:第一种,发现一个有效字符就添加‘/’;第二种,还是将所有有效字符存储成一个list,最后返回时统一添加分隔符 ‘/’。好像第二种更好理解,运行时间稍微短一点

代码

 第一种风格

class Solution:
    def simplifyPath(self, path):
        """
        :type path: str
        :rtype: str
        """
        path.replace('//', '/')
        list = path.split('/')
        res = '/'
        num = []
        for i in range(len(list)):
            if list[i] == '..' and len(res) > 1:
                res = res[:len(res) - num[-1] - 1]
                num=num[:-1]
            elif list[i] != '' and list[i] != '.' and list[i] != '..':
                res = res + list[i] + '/'
                num.append(len(list[i]))
        return res[:-1] if len(res) > 1 else res

第二种风格:

class Solution:
    def simplifyPath(self, path):
        """
        :type path: str
        :rtype: str
        """
        path.replace('//', '/')
        list = path.split('/')
        res =[]
        for i in range(len(list)):
            if list[i] == '..' and len(res) > 0:
                res = res[:-1]
            elif list[i] != '' and list[i] != '.' and list[i] != '..':
                res.append(list[i])
        return '/'+'/'.join(res)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Briwisdom

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值