1. 程式人生 > >LeetCode:簡化路徑(Simplify Path)

LeetCode:簡化路徑(Simplify Path)

題目:

Given an absolute path for a file (Unix-style), simplify it.

For example,

path = "/home/", => "/home"

path = "/a/./b/../../c/", => "/c"

Corner Cases:

Did you consider the case where path = "/../"?

In this case, you should return "/".

Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".

In this case, you should ignore redundant slashes and return "/home/foo".

這道題的要求是簡化一個Unix風格下的檔案的絕對路徑。

字串處理,由於".."是返回上級目錄(如果是根目錄則不處理),因此可以考慮用棧記錄路徑名,以便於處理。需要注意幾個細節:

  • 重複連續出現的'/',只按1個處理,即跳過重複連續出現的'/';
  • 如果路徑名是".",則不處理;
  • 如果路徑名是"..",則需要彈棧,如果棧為空,則不做處理;
  • 如果路徑名為其他字串,入棧。
  • 最後,再逐個取出棧中元素(即已儲存的路徑名),用'/'分隔並連線起來,不過要注意順序呦。

思路:

1. 將字串按“/”劃分,存入陣列。

2. 將有意義的字串入棧,如果遇到“..”則出棧。

3. 最後將棧中剩餘字串以"/"連線,並返回。未空預設返回“/”

程式碼(Python):時間O(n), 空間O(n)

class Solution(object):
    def simplifyPath(self, path):
        """
        :type path: str
        :rtype: str
        """
        path_array = path.split("/")
        stack = []
        res_path = ""
        for item in path_array:
            if item not in ["",".",".."]:
                stack.append(item) 
            if ".." == item and stack: 
                stack.pop(-1)
        if []==stack: 
            return "/"
        for item in stack:
            res_path += "/"+item + ""
        return res_path