精简Linux文件路径

精简Linux的文件路径:

  1. ..回退的功能
  2. .留在当前目录
  3. //只保留一个/
  4. abc/..要返回.
  5. 报错
  6. 删除最后一个/
主要思路: string.split,注意开始是/或者../或者./等三种不同情况。用栈记录路径的起始位置,讨论/后的不同情况即可:
 
class Solution:
    def linux_path_compress(self, path):
        is_root = path.startswith('/')
        folders = path.split('/')
        f = []
        for folder in folders:
            if (folder == '..'):
                if (not f and is_root):
                    return False, ''
                elif ((not f and not is_root) or (f and f[-1] == '..')):
                    f.append(folder)
                elif (f):
                    f.pop()
            elif (folder and folder != '.'):
                f.append(folder)
        mid = '/'.join(f) + '/'
        prefix = '/' if is_root else './'
        if (f and f[0] == '..'):
            prefix = ''
        return True, prefix + mid

s = Solution()
a = "/.abc/xxx./abc/bacd/.././bcd/fsgs/../../../x/y/z/../../../../.././././xda"
b = "asdf/.abc/xxx./abc/bacd/.././bcd/fsgs/../../../x/y/z/../../../../../../.././../.././././"
c = "/xyz/./bcd/fsgs/../../../x/y/z/../../../.."
d = "../../../etc/xyz/../abc/////////////////////////////.asdf/../../../../"
print(s.linux_path_compress(a)) #(True, '/xda/')
print(s.linux_path_compress(b)) #(True, '../../../')
print(s.linux_path_compress(c)) #(False, '')
print(s.linux_path_compress(d)) #(True, '../../../../')

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值