题目描述(中等)
给定一个文档 (Unix-style) 的完全路径,请进行路径简化。
例如,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
边界情况:
- 你是否考虑了 路径 =
"/../"
的情况?
在这种情况下,你需返回"/"
。 - 此外,路径中也可能包含多个斜杠
'/'
,如"/home//foo/"
。
在这种情况下,你可忽略多余的斜杠,返回"/home/foo"
。
思路分析
把几种边界情况考虑清楚即可:
- 如果是‘.’,则自动去除
- 如果是‘..’,则把前一个有效字符去除
- 如果是多个连续斜杠‘/’,则去除这些斜杠“/”
根据这几个限定,编码实现都是先通过‘/’将有效字符分割出来,接下来可以采用两种风格编码:第一种,发现一个有效字符就添加‘/’;第二种,还是将所有有效字符存储成一个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)