【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
相关推荐
Kevinyu101122 分钟前
P6149 [USACO20FEB] Triangles S题解
算法
arin87632 分钟前
【组合】矩阵ksm+状压dp
算法·矩阵·深度优先
我爱豆子36 分钟前
Leetcode Hot 100刷题记录 -Day14(矩阵置0)
java·算法·leetcode·矩阵
武昌库里写JAVA1 小时前
99AutoML 自动化机器学习实践--NNI 自动化机器学习工具包
c语言·开发语言·数据结构·算法·二维数组
小李很执着2 小时前
【深度智能】:迈向高级时代的人工智能全景指南
人工智能·python·深度学习·算法·机器学习·语言模型
IT规划师2 小时前
LeetCode题集-4 - 寻找两个有序数组的中位数,图文并茂,六种解法,万字讲解
leetcode·中位数
程序猿练习生2 小时前
C++速通LeetCode简单第9题-二叉树的最大深度
c++·算法·leetcode
小陶 coding3 小时前
代码随想录刷题day32丨动态规划理论基础,509. 斐波那契数, 70. 爬楼梯, 746. 使用最小花费爬楼梯
java·数据结构·算法·leetcode·动态规划
翟天保Steven3 小时前
CUDA-中值滤波算法
算法·计算机视觉
Python私教3 小时前
Go语言现代web开发09 for 循环语句
java·算法·golang