【LeetCode】71.简化路径

1. 题目

2. 分析

3. 代码

我写了一版很复杂的代码:

python 复制代码
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
相关推荐
pride.li3 分钟前
第12章 Python 教程-流程控制:循环结构
linux·服务器·python·算法
海绵宝宝转agent27 分钟前
2026-10-16 4算法+1面经
算法
小poop1 小时前
基础排序算法详解——插入、选择与交换排序
算法·排序算法
青蓝智慧马老师1 小时前
想学数据分析但零基础,正确顺序不是先学 Python
大数据·人工智能·算法
jeo陽1 小时前
05-数组与冒泡排序:第一个数据结构与经典算法
c语言·数据结构·算法
鸽鸽程序猿1 小时前
【刷题册】hot21-25
算法
Keven_111 小时前
算法札记:记忆化搜索中面对多组数据的初始化
算法
埃伊蟹黄面1 小时前
面试常问题目 —— STL
c++·面试·职场和发展·stl
happyprince1 小时前
02-具体观 · JevAny算法与实现剖析
人工智能·算法
Nil2081 小时前
leetcode 75颜色分类
数据结构·算法·leetcode