【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
相关推荐
scx2013100427 分钟前
20251201换根DP总结
算法·动态规划·换根dp
zd20057230 分钟前
STREAMS指南:环境及宿主相关微生物组研究中的技术报告标准
人工智能·python·算法
TechNomad37 分钟前
排序算法:基数排序算法
算法·排序算法
努力学算法的蒟蒻43 分钟前
day43(12.24)——leetcode面试经典150
算法·leetcode·面试
jianfeng_zhu1 小时前
二叉树的一些基本运算
算法
元亓亓亓1 小时前
LeetCode--279. 完全平方数--中等
算法·leetcode·动态规划
TimberWill1 小时前
哈希-03-字母异位词分组
算法·哈希算法
轻微的风格艾丝凡1 小时前
matlab推导QPR离散公式并验证
算法·matlab·谐振
岁岁的O泡奶2 小时前
NSSCTF_crypto_[SWPU 2020]happy
经验分享·python·算法·密码学
EchoL、2 小时前
【论文阅读】SteganoGAN:High Capacity Image Steganography with GANs
论文阅读·人工智能·笔记·算法