【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
相关推荐
wenyq71 小时前
LeetCode 2460. Apply Operations to an Array
算法·leetcode
.格子衫.2 小时前
032动态规划之区间DP——算法备赛
算法·动态规划
青 春 记 忆2 小时前
LeetCode 142. 环形链表 II|Python 解法详解
python·leetcode·链表
不会代码的小猴3 小时前
7. JSON
开发语言·c++·笔记·qt·算法·json
怪奇云呼军4 小时前
知识库也会注入指令?闪电智能VoiceAgent 如何防住 Prompt Injection
人工智能·python·算法·云计算·音视频
阿里云大数据AI技术4 小时前
基于 EMR Serverless Ray 实现 Qwen 模型批量推理实践
人工智能·算法·agent
Rambo.xia5 小时前
为什么去马赛克算法,决定了ISP的画质上限
算法·接口隔离原则
Benny_Tang5 小时前
题解:P10230 [COCI 2023/2024 #4] Lepeze
c++·算法
Geek-Chow5 小时前
06 训练管线:数据如何变成权重
人工智能·算法