[leetcode]Simplify Path @ Python


原題地址:https://oj.leetcode.com/problems/simplify-path/

題意:

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.

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下的最簡路徑,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

代碼二:

利用python的字符串處理能力。

class Solution:
    # @param path, a string
    # @return a string
    def simplifyPath(self, path):
        path = path.split('/')
        curr = '/'
        for i in path:
            if i == '..':
                if curr != '/':
                    curr = '/'.join(curr.split('/')[:-1])
                    if curr == '': curr = '/'
            elif i != '.' and i != '':
                curr += '/' + i if curr != '/' else i
        return curr

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM