【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
相关推荐
逸风尊者1 分钟前
XGBoost模型工程使用
java·后端·算法
LUVK_10 分钟前
第七章查找
数据结构·c++·考研·算法·408
khalil102016 分钟前
代码随想录算法训练营Day-31贪心算法 | 56. 合并区间、738. 单调递增的数字、968. 监控二叉树
数据结构·c++·算法·leetcode·贪心算法·二叉树·递归
lihihi1 小时前
P9936 [NFLSPC #6] 等差数列
算法
啊我不会诶1 小时前
2024ICPC西安邀请赛补题
c++·算法
谭欣辰1 小时前
C++ 版Dijkstra 算法详解
c++·算法·图论
yuan199971 小时前
C&CG(列与约束生成)算法,来解决“风光随机性”下的微网鲁棒配置问题
c语言·开发语言·算法
wayz112 小时前
Day 11 编程实战:XGBoost金融预测与调参
算法·机器学习·金融·集成学习·boosting
念越2 小时前
算法每日一题 Day07|双指针求解和为S的两个数
算法·力扣
qeen872 小时前
【算法笔记】双指针及其经典例题解析
c++·笔记·算法·双指针