【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
相关推荐
小柴狗20 分钟前
C语言关键字详解:static、const、volatile
算法
仙俊红2 小时前
LeetCode每日一题,20250914
算法·leetcode·职场和发展
风中的微尘9 小时前
39.网络流入门
开发语言·网络·c++·算法
西红柿维生素10 小时前
JVM相关总结
java·jvm·算法
ChillJavaGuy11 小时前
常见限流算法详解与对比
java·算法·限流算法
sali-tec11 小时前
C# 基于halcon的视觉工作流-章34-环状测量
开发语言·图像处理·算法·计算机视觉·c#
你怎么知道我是队长13 小时前
C语言---循环结构
c语言·开发语言·算法
艾醒13 小时前
大模型面试题剖析:RAG中的文本分割策略
人工智能·算法
纪元A梦15 小时前
贪心算法应用:K-Means++初始化详解
算法·贪心算法·kmeans
_不会dp不改名_15 小时前
leetcode_21 合并两个有序链表
算法·leetcode·链表