题目来源:
LeetCode题目:71. 简化路径 - 力扣(LeetCode)
解题思路:
按要求处理即可。碰到 多个斜杠以 一个斜杆代替;碰到 "\." 删去当前目录;碰到 "\.." 删去当前及上一个目录。
解题代码:
#python3
class Solution:
def allForwardSlash(string:str)->bool:
for each in string:
if each!="/":
return False
return True
def deleteLastFoowardSlash(string:str)->str:
if len(string)==0:
return string
pos=len(string)-1
for i in range(len(string)-1,-1,-1):
if string[i]=="/":
pos=i
break
return string[0:pos]
def simplifyPath(self, path: str) -> str:
res=""
temp=""
for each in path:
if each=="/":
print(temp)
if Solution.allForwardSlash(temp):
temp="/"
elif temp=="/.":
temp="/"
elif temp=="/..":
res=Solution.deleteLastFoowardSlash(res)
temp="/"
else:
res=res+temp
temp="/"
else:
temp=temp+each
if temp=="/..":
res=Solution.deleteLastFoowardSlash(res)
elif temp!="/" and temp!="/.":
res=res+temp
if len(res)==0:
res="/"
return res
总结:
应该直接用 / 分割字符串,将分割后的字符串数组中存在的空串、 "." 、".."及其上一个有意义的字符串 删去,最后再拼接。
官方题解是用栈分割再拼接。