【LeetCode 中等题】36-简化路径

题目描述:给定一个文档 (Unix-style) 的完全路径,请进行路径简化。

例如,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

边界情况:

  • 你是否考虑了 路径 = "/../" 的情况?
    在这种情况下,你需返回 "/" 。
  • 此外,路径中也可能包含多个斜杠 '/' ,如 "/home//foo/" 。
    在这种情况下,你可忽略多余的斜杠,返回 "/home/foo" 。

解法1。输入是一个个基本字符组成的字符串,遍历是基本,关键是如何制定遍历规则。遇到/就继续,知道遇到字符,记录下正常字符的起止index,判断是否为..或.,如果是..就要pop出栈顶,如果是.就不管,反之压栈。

class Solution(object):
    def simplifyPath(self, path):
        """
        :type path: str
        :rtype: str
        """
        len_p = len(path)
        if not path or len_p == 0:
            return '/'
        valid_str = []
        i = 0
        while i < len_p:
            while i < len_p and path[i] == '/':
                i += 1
            if i == len_p:
                break
            start = i
            while i < len_p and path[i] != '/':
                i += 1
            end = i
            sub_str = path[start:end]
            if sub_str == '..':
                if valid_str:
                    valid_str.pop()
            elif sub_str != '.':
                valid_str.append(sub_str)
        if not valid_str:
            return '/'
        res = ''
        for c in valid_str:
            res += '/'+c
        return res

解法2。一种更简略的做法

class Solution(object):
    def simplifyPath(self, path):
        """
        :type path: str
        :rtype: str
        """
        len_p = len(path)
        if not path or len_p == 0:
            return '/'
        valid_str = [i for i in path.split('/') if i]
        stack = []
        for i in valid_str:
            if i == '.':
                continue
            elif i == '..':
                if stack:
                    stack.pop()
            else:
                stack.append(i)
        return '/'+ '/'.join(stack)

猜你喜欢

转载自blog.csdn.net/weixin_41011942/article/details/85698636