[LeetCode]题解(python):071-Simplify Path

时间:2022-01-24 15:52:12

题目来源:

  https://leetcode.com/problems/simplify-path/


题意分析:

  简化Unix上的绝对路径,也就是多个'/'代表一个,'..'表示返回上一级目录,‘.'代表当前目录。


题目思路:

  利用栈,把非'/'和'.'push进栈,如果遇到'..'pop掉一个,否则继续push进去。最后还原成路径格式。


代码(Python):

  

class Solution(object):
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
stack,i,ans = [],0,''
while i < len(path):
j = i + 1
while j < len(path) and path[j] != '/':
j += 1
tmp = path[i + 1:j]
if tmp != '':
if tmp == '..':
if stack !=[]:
stack.pop()
elif tmp != '.':
stack.append(tmp)
i = j
if stack == []:
return '/'
for k in stack:
ans += '/' + k
return ans

转载请注明出处:http://www.cnblogs.com/chruny/p/5069660.html