1. 程式人生 > 實用技巧 >Leetcode 71 Simplify Path

Leetcode 71 Simplify Path

題目介紹

將不規範的Unix路徑改為規範的路徑。其中..代表回到上級目錄,.代表當前目錄。

Examples:

Input: "/home/"
Output: "/home   # 最後不應當有斜線
  
Input: "/../"
Output: "/"
  
Input: "/home//foo/"
Output: "/home/foo"   # 去除多餘的斜線
  
Input: "/a/./b/../../c/"
Output: "/c"          # a->b->a->/->c

Input: "/a//b////c/d//././/.."
Output: "/a/b/c"       # a->b->c->d->c

Solution

可以利用棧來實現,如果出現..,則彈出,如果是.,不進行操作,如果非空,則入棧。

沒有用split的實現:

class Solution(object):
    def simplifyPath(self, path):
        """
        :type path: str
        :rtype: str
        """
        stack = []

        i = 0
        while i < len(path):
            j = i+1
            while j < len(path) and path[j] != '/':
                j += 1
            words = path[i+1:j]
            if words == '..':
                if stack:
                    stack.pop()
            elif words == '.' or not words:
                pass
            else:
                stack.append(words)
            i = j
        res = ''
        while stack:
            res = '/' + stack.pop() + res
        if not res:
            res = '/'
            
        return res

如果結果為空,則返回根目錄。

使用split,更加優雅一點:

class Solution(object):
    def simplifyPath(self, path):
        """
        :type path: str
        :rtype: str
        """
        stack = []

        dirs = path.split('/')
        for dir in dirs:
            if dir == '..':
                if stack:
                    stack.pop()
            elif dir == '.' or not dir:
                pass
            else:
                stack.append(dir)
        res = ''
        while stack:
            res = '/' + stack.pop() + res
        if not res:
            res = '/'
            
        return res