Description

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

For example,

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

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

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

In a UNIX-style file system, a period (.) refers to the current directory, so it can be ignored in a simplified path. Additionally, a double period ("..") moves up a directory, so it cancels out whatever the last directory was. For more information, look here.

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下的路徑)字元串,簡化此字元串。

舉例:

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

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

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

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

在UNIX的文件系統中,英文句點(.)表示當前目錄,因此在簡化絕對路徑時可以忽略它。 並且,一個雙英文句點("..")表示向上移動一個目錄,因此返回了雙句點前面的路徑。 有關Unix系統文件路徑的更多信息,請移步這裡.

思路

  • 這道題目主要使用了棧這種數據結構.
  • 我們首先拆分字元串,以"/"為拆分依據(python中可以直接使用拆分函數).
  • 我們聲明一個數組形式的棧stack,然後我們依次檢查每一個元素.
  1. 如果當前位置是".",則什麼也不做.
  2. 如果當前位置是"..",從stack中pop出一個元素(如果stack中有數據,如果沒有,什麼也不做)
  3. 如果不是以上兩種情況,把當前元素壓入棧.
  4. 最後以"/"為連接元素,把棧中的所有元素連接成一個字元串.

class Solution:
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
# 如果path為空,返回Nonoe
if not path:
return None
# 以"/"拆分字元串
path = path.split("/")
# 聲明一個空棧
stack = []
# 依次檢查每一個元素
for item in path:
# 這裡使用的是python3自帶的拆分函數,會返回空值,所以需要判斷一下
# 如果是空值或者"."則什麼也不做
if not item or item == .:
continue
# 如果是".."
elif item == "..":
# 如果棧不空,則彈出棧頂元素
if stack:
stack.pop()
# 如果不為空,不是".",不是".."則壓入棧
else:
stack.append(item)
# 用"/"連接所有元素,返回
return /+/.join(stack)

源代碼文件在這裡.

?本文首發於何睿的博客,歡迎轉載,轉載需保留文章來源,作者信息和本聲明.
推薦閱讀:
相關文章