【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
相关推荐
短剑重铸之日5 分钟前
《RocketMQ研读》面试篇
java·后端·面试·职场和发展·rocketmq
充值修改昵称7 分钟前
数据结构基础:B+树如何优化数据库性能
数据结构·b树·python·算法
Cinema KI7 分钟前
一键定位,哈希桶的极速魔法
数据结构·c++·算法·哈希算法
曾几何时`13 分钟前
二分查找(九)2300. 咒语和药水的成功对数
数据结构·算法
We་ct30 分钟前
LeetCode 12. 整数转罗马数字:从逐位实现到规则复用优化
前端·算法·leetcode·typescript
绿算技术33 分钟前
重塑智算存储范式:绿算技术NVMe-oF芯片解决方案全景剖析
人工智能·算法·gpu算力
sin_hielo1 小时前
leetcode 3510
数据结构·算法·leetcode
努力学算法的蒟蒻1 小时前
day64(1.23)——leetcode面试经典150
面试·职场和发展
Anastasiozzzz1 小时前
力扣hot100 20.有效的括号 解析
java·算法·面试·力扣
CrazyClaz1 小时前
负载均衡算法
算法·负载均衡