题解 | 「力扣」第 71 题:简化路径(中等、栈)

194 阅读1分钟

摘要:这里依然是要突出「栈」的作用。「简化路径」的操作恰好符合了「后进先出」的规律,因此需要使用到「栈」。

Python 代码:

def simplifyPath(path):
    lst = []
    splits = path.split("/")
    
    for s in splits:
        if s == "":
            continue
        if s == ".":
            continue
            
        if s == "..":
            if len(lst) != 0:
                lst.pop()
        else:
            lst.append(s)
    
    result = []
    if len(lst) == 0:
        return "/"
    result = ['/' + i for i in lst]
    return ''.join(result)