1. 题目
2. 分析
3. 代码
我写了一版很复杂的代码:
class Solution:
def simplifyPath(self, path: str) -> str:
operator = [] # 操作符的栈
dir_name = [] # 文件名的栈
idx = 0
cur_dir_name = ""
while(idx < len(path)):
if path[idx] == '/':
operator.append('/')
cur_dir_name = "" # init
next_idx = idx+1
while(next_idx < len(path) and path[next_idx]!='/'):
cur_dir_name += path[next_idx]
next_idx+=1
# 获取dir_name
if cur_dir_name == ".":
operator.pop()
elif cur_dir_name == "..":
if len(operator):
operator.pop()
if len(dir_name):
dir_name.pop()
elif cur_dir_name != "":
dir_name.append(cur_dir_name)
elif cur_dir_name == "":
operator.pop()
idx = next_idx
# 输出最后结果
res = ""
for i in range(len(operator)):
if i < len(dir_name):
res += (operator[i] + dir_name[i])
if res == "":
res = "/"
return res