【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
相关推荐
alphaTao5 分钟前
LeetCode 每日一题 2026/2/2-2026/2/8
算法·leetcode
甄心爱学习9 分钟前
【leetcode】判断平衡二叉树
python·算法·leetcode
颜酱18 分钟前
从二叉树到衍生结构:5种高频树结构原理+解析
javascript·后端·算法
不知名XL37 分钟前
day50 单调栈
数据结构·算法·leetcode
@––––––1 小时前
力扣hot100—系列2-多维动态规划
算法·leetcode·动态规划
xsyaaaan1 小时前
代码随想录Day31动态规划:1049最后一块石头的重量II_494目标和_474一和零
算法·动态规划
Jay Kay2 小时前
GVPO:Group Variance Policy Optimization
人工智能·算法·机器学习
Epiphany.5562 小时前
蓝桥杯备赛题目-----爆破
算法·职场和发展·蓝桥杯
YuTaoShao2 小时前
【LeetCode 每日一题】1653. 使字符串平衡的最少删除次数——(解法三)DP 空间优化
算法·leetcode·职场和发展
茉莉玫瑰花茶2 小时前
C++ 17 详细特性解析(5)
开发语言·c++·算法