2025/3/21 【栈与队列】LeetCode71.简化路径 【√】

python解法

class Solution:
    def simplifyPath(self, path: str) -> str:
        path1 = path.split('/')
        path2 = []
        for item in path1:
            if item == '' or item == '.':
                continue
            elif item == '..':
                if len(path2) > 0:
                    path2.pop()
            else:
                path2.append(item)
            
        if len(path2) == 0:
            return "/"
        else:
            return "/" + "/".join(path2)

join函数可以接受空列表。

官方题解的简化版本:

class Solution:
    def simplifyPath(self, path: str) -> str:
        path1 = path.split('/')
        stack = []

        for item in path1:
            if item == '..':
                if stack:
                    stack.pop()
            elif item and item != '.':
                stack.append(item)  

        return "/" + "/".join(stack)

注意:对于以上的简化版本代码,假设将 ifelif 的内容交换:,会出现错误:

错误的示例:

def simplifyPath(path: str) -> str:
    path1 = path.split('/')
    stack = []

    for item in path1:
        if item and item != '.':
            stack.append(item)
        elif item == "..":
            if len(stack) > 0:
                stack.pop()

        print(stack)

    return '/' + '/'.join(stack)

在这个版本中,if item and item != '.' 会首先执行,这意味着即使是 .. 也会被压入栈中(除非它是空字符串或 .),这显然不符合预期的行为。

 

这道题,我第一天下午做的时候想着从快慢指针的思路去做,但是判断单个的 “/” 和多个的 “//··”,配合队列,栈要连续出栈,入栈太麻烦了,还是用split函数把 / 全都去掉就方便多了,总算做出来了,今日有所得,哈哈哈哈哈哈哈哈哈哈!太棒了!爱我自己❤

posted @ 2025-03-21 18:17  axuu  阅读(6)  评论(0)    收藏  举报