【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
相关推荐
zephyr051 小时前
动态规划-最长上升子序列问题
算法·动态规划
闪电悠米2 小时前
力扣hot100-56.合并区间-排序详解
数据结构·算法·leetcode·贪心算法·排序算法
卡提西亚3 小时前
leetcode-1438. 绝对差不超过限制的最长连续子数组
算法·leetcode·职场和发展
Java面试题总结3 小时前
LeetCode 93.复原IP地址
算法·leetcode·职场和发展·.net
从零开始的代码生活_4 小时前
C++ 多态详解:虚函数、动态绑定、抽象类与虚表原理
开发语言·c++·后端·学习·算法
泷寂4 小时前
最小生成树 (MST基础)
算法
Daniel_1235 小时前
数组——总结篇
算法
不懒不懒5 小时前
【针对路面识别数据集,结合三轴加速度标准化数据及多路面识别需求,以下是算法选择与处理方案】
算法
Reart5 小时前
Leetcode 121. 买卖股票的最佳时机(717)
后端·算法
会编程的小孩5 小时前
初识数据类型以及变量定义
数据结构·算法