【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
相关推荐
xsyaaaan3 小时前
leetcode-hot100-双指针:283移动零-11盛最多水的容器-15三数之和-42接雨水
算法·leetcode
炽烈小老头6 小时前
【每天学习一点算法 2026/03/08】相交链表
学习·算法·链表
一碗白开水一7 小时前
【工具相关】OpenClaw 配置使用飞书:打造智能飞书助手全流程指南(亲测有效,放心享用)
人工智能·深度学习·算法·飞书
仰泳的熊猫7 小时前
题目2194:蓝桥杯2018年第九届真题-递增三元组
数据结构·c++·算法
Tisfy7 小时前
LeetCode 1888.使二进制字符串字符交替的最少反转次数:前缀和O(1)
算法·leetcode·字符串·题解
滴滴答滴答答8 小时前
机考刷题之 9 LeetCode 503 下一个更大元素 II
算法·leetcode·职场和发展
飞Link8 小时前
梯度下降的优化算法中,动量算法和指数加权平均的区别对比
人工智能·深度学习·算法
啊哦呃咦唔鱼8 小时前
LeetCode hot100-15 三数之和
数据结构·算法·leetcode
_日拱一卒8 小时前
LeetCode(力扣):杨辉三角||
算法·leetcode·职场和发展
rqtz8 小时前
基于I2C总线的IMU-磁力计融合算法与数据共享
算法·iic·espidf·qmc5883p·icm42670p·imu磁力计融合