不知道要拿来做什么但觉得很有意思的个人博客
71. 简化路径
71. 简化路径

71. 简化路径

给你一个字符串 path ,表示指向某一文件或目录的 Unix 风格 绝对路径 (以 ‘/’ 开头),请你将其转化为更加简洁的规范路径。

在 Unix 风格的文件系统中,一个点(.)表示当前目录本身;此外,两个点 (..) 表示将目录切换到上一级(指向父目录);两者都可以是复杂相对路径的组成部分。任意多个连续的斜杠(即,’//’)都被视为单个斜杠 ‘/’ 。 对于此问题,任何其他格式的点(例如,’…’)均被视为文件/目录名称。

请注意,返回的 规范路径 必须遵循下述格式:

始终以斜杠 ‘/’ 开头。
两个目录名之间必须只有一个斜杠 ‘/’ 。
最后一个目录名(如果存在)不能 以 ‘/’ 结尾。
此外,路径仅包含从根目录到目标文件或目录的路径上的目录(即,不含 ‘.’ 或 ‘..’)。
返回简化后得到的 规范路径 。

简单的栈模拟,然而在预处理的过程有很多细节需要注意,重复开头”///”等问题。

class Solution:
    def simplifyPath(self, path: str) -> str:
        # 重组放入path_list,丢弃"//"
        path_list = []
        n = len(path)
        left = 0
        right = 1
        while True:
            if left == n - 1:
                return "/"
            if path[left] == '/':
                left += 1
                right += 1
                continue
            left -= 1
            right -= 1
            break
        while right < n - 1:
            if path[right] == '/' and not path[right + 1] == '/':
                path_list.append(path[left+1: right].replace("/",""))
                left = right
            right += 1
        if path[right] == '/':
            path_list.append(path[left+1: right].replace("/",""))
        else:
            path_list.append(path[left+1: right+1].replace("/",""))
        print(path_list)
        res = []
        # 判断父级目录或当前目录
        for index, cur_dir in enumerate(path_list):
            if cur_dir == '.':
                continue
            if cur_dir == '..' and len(res) > 0:
                res.pop()
                continue
            if cur_dir == '..':
                continue
            res.append(cur_dir)
        # 重组输出答案
        if res == []:
            return '/'
        res_str = ''
        for single_res in res:
            res_str += '/' + single_res

        return res_str
          

力扣标答:

class Solution:
    def simplifyPath(self, path: str) -> str:
        names = path.split("/")
        stack = list()
        for name in names:
            if name == "..":
                if stack:
                    stack.pop()
            elif name and name != ".":
                stack.append(name)
        return "/" + "/".join(stack)

忘记python自带split函数,手动分组出现很多问题。字符串的.join()可以运用。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/simplify-path
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

发表评论

您的电子邮箱地址不会被公开。