算法分析與設計課程(10):【leetcode】Simplify Path

Description:

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

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

click to show corner cases.

算法分析:

題目的要求是輸出Unix下的最簡路徑,Unix文件的根目錄爲"/","."表示當前目錄,".."表示上級目錄。

例如:

輸入1:

/../a/b/c/./.. 

輸出1:

/a/b

模擬整個過程:

1. "/" 根目錄

2. ".." 跳轉上級目錄,上級目錄爲空,所以依舊處於 "/"

3. "a" 進入子目錄a,目前處於 "/a"

4. "b" 進入子目錄b,目前處於 "/a/b"

5. "c" 進入子目錄c,目前處於 "/a/b/c"

6. "." 當前目錄,不操作,仍處於 "/a/b/c"

7. ".." 返回上級目錄,最終爲 "/a/b"

使用一個棧來解決問題。遇到'..'彈棧,遇到'.'不操作,其他情況下壓棧。

代碼如下:

class Solution:
    # @param path, a string
    # @return a string
    def simplifyPath(self, path):
        stack = []
        i = 0
        res = ''
        while i < len(path):
            end = i+1
            while end < len(path) and path[end] != "/":
                end += 1
            sub=path[i+1:end]
            if len(sub) > 0:
                if sub == "..":
                    if stack != []: stack.pop()
                elif sub != ".":
                    stack.append(sub)
            i = end
        if stack == []: return "/"
        for i in stack:
            res += "/"+i
        return res






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章