【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
相关推荐
Miraitowa_cheems5 分钟前
LeetCode算法日记 - Day 73: 最小路径和、地下城游戏
数据结构·算法·leetcode·职场和发展·深度优先·动态规划·推荐算法
野蛮人6号9 分钟前
力扣热题100道之560和位K的子数组
数据结构·算法·leetcode
Swift社区1 小时前
LeetCode 400 - 第 N 位数字
算法·leetcode·职场和发展
fengfuyao9852 小时前
BCH码编译码仿真与误码率性能分析
算法
小白不想白a2 小时前
每日手撕算法--哈希映射/链表存储数求和
数据结构·算法
剪一朵云爱着2 小时前
力扣2080. 区间内查询数字的频率
算法·leetcode
落日漫游2 小时前
数据结构笔试核心考点
java·开发语言·算法
Dream it possible!3 小时前
LeetCode 面试经典 150_栈_有效的括号(52_20_C++_简单)(栈+哈希表)
c++·leetcode·面试··哈希表
workflower3 小时前
Fundamentals of Architectural Styles and patterns
开发语言·算法·django·bug·结对编程
仰泳的熊猫3 小时前
LeetCode:701. 二叉搜索树中的插入操作
数据结构·c++·算法·leetcode