精简Linux的文件路径:
- ..回退的功能
- .留在当前目录
- //只保留一个/
- abc/..要返回.
- 报错
- 删除最后一个/
主要思路: 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, '../../../../')