- 题目要求:
-
思路:
- 把字符串以"/"作为分隔符保存成数组
- 定义一个res数组用来保存返回的结果
- 遍历这个数组,如果当前的值为".",则pass
- 如果当前值为"..",pop出res的最后一个元素
- 其他情况(当前值为目录名),把他append到res中
- 最后把res中的元素用"/"拼接在一起
- 在头加一个"/"
- 核心代码:
#定义res数组用来保存结果集
res = []
#把给定的字符串按"/"分开
mypath = path.split('/')
#遍历分割后的数组
for i in mypath:
#如果当前的值存在(可能给定的字符串有连续的两个以上"/")
if i :
#如果当前值为".",跳过
if i == ".":
pass
#如果当前值为"..",而且res不为空,pop出res的最后一个元素
elif i == "..":
if res:
res.pop()
#如果其他情况(当前值为目录名),把他加到结果集里
else:
res.append(i)
#最后把结果集拼起来,注意开头要有一个"/"
result ='/' + '/'.join(res)
return result
- 完整代码:
class Solution(object):
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
res = []
mypath = path.split('/')
print mypath
for i in mypath:
if i :
if i == ".":
pass
elif i == "..":
if res:
res.pop()
else:
res.append(i)
result ='/' + '/'.join(res)
return result
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。