71. 简化路径

exiaohu 于 2022-01-06 发布

题目链接:71. 简化路

解法一

调库。

import os.path


class Solution:
    def simplifyPath(self, path: str) -> str:
        return os.path.normpath(path)

解法二

遍历一下。

class Solution:
    def simplifyPath(self, path: str) -> str:
        normalized_path = []

        for p in path.split('/'):
            if p in ['', '.']:
                continue
            elif p in ['..']:
                try:
                    normalized_path.pop()
                except IndexError:
                    pass
            else:
                normalized_path.append(p)
        return '/' + '/'.join(normalized_path)