给定一个文件的绝对路径(unix系统),将其简化。
在unix文件系统中,’.’ 表示当前目录,因此可以被忽略。’…’ 表示上一个目录,因此需要取消掉最后一层目录。
示例:
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
path = "/a/../../b/../c//.//", => "/c"
path = "/a//b////c/d//././/..", => "/a/b/c"
边界示例:
- “/…/” 应该返回 “/”
- 多个斜线应该合为一个,如 “/home//foo/” 应该返回 “/home/foo”
思路
先将斜线之间的目录按顺序提取出来,并定义一个空的结果路径,然后从左到右进行遍历。
- 如果遇到 ‘.’,则跳过,继续遍历。
- 如果遇到 ‘…’,则结果路径中的最后一个路径删掉,继续遍历。
- 否则,将此路径添加到结果路径中,继续遍历。
最后,需要注意两个边界示例,因此在按斜线分隔之前,先将多个斜线合为一个(用正则式匹配和替换);在遍历结束之后,若为空路径,则改为’/’;若最后一个字符为斜线,则去掉。
python实现
import re
def simplifyPath(path):
"""
:type path: str
:rtype: str
先将斜线之间的目录按顺序提取出来,然后从左到右进行 . 和 .. 的分析。
"""
# 将多个斜线换成1个
pattern = re.compile(r'/{2,}')
path = re.sub(pattern, '/', path)
# 分割
splits = path.split('/')
results = []
for split in splits:
if (split == '..' and len(results) == 1) or (split == '.'):
continue
if split == '..':
results = results[:-1]
else:
results.append(split)
result = '/'.join(results)
if result == '': # 为空时返回一个斜杠
result = '/'
elif len(result) > 1 and result[-1] == '/': # 去掉最后一个斜杠
result = result[:-1]
return result
if '__main__' == __name__:
path = "/"
print(simplifyPath(path))