leetcode71

 1 class Solution:
 2     def simplifyPath(self, path: str) -> str:
 3         ary = path.split('/')
 4         #print(ary)
 5         n = len(ary)
 6         st = []#默认第一个字符是/
 7         for i in range(n):
 8             cur = ary[i]
 9             if cur == '' or cur == '.':
10                 continue
11             elif cur == '..':
12                 if len(st) > 1:
13                     st.pop(-1)
14                     st.pop(-1)
15             else:
16                 st.append('/')
17                 st.append(cur)
18         if len(st) > 1 and st[-1] == '/':
19             st.pop(-1)
20         if len(st) == 0:
21             st.append('/')
22         return ''.join(st)

使用栈存储,在遇到 '..'的时候出栈,在遇到目录的时候入栈,遇到空白字符或者'.'的时候不处理。

原文地址:https://www.cnblogs.com/asenyang/p/12017358.html