

栈
思路:
先按‘/’将path拆分为数组,构建一个栈,遍历数组,如果数组中的元素不为空且不等于‘ . ’,则将元素压入栈中,如果数组中元素等于‘ .. ’,则将栈顶元素推出。遍历完成后,从栈底开始,每个元素前加‘/’构建字符串,得到最后结果。
代码:
class Solution:
def simplifyPath(self, path: str) -> str:
temp = path.split(‘/‘)
res = []
ans = ‘‘
for c in temp:
if c == ‘..‘:
if res:
res.pop()
elif c!=‘‘ and c!=‘.‘:
res.append(c)
if not res:
ans = ‘/‘
for i in range(len(res)):
ans += (‘/‘+res[i])
return ans
原文:https://www.cnblogs.com/nilhxzcode/p/13085131.html