【題目】
Given an absolute path for a file(Unix-style), simplify it.
For example,
path = "/home/", =>"/home"
path = "/a/./b/../../c/", =>"/c"
簡化Unix上的絕對路徑,也就是多個'/'代表一個,'..'表示返回上一級目錄,‘.'代表當前目錄。
【思路】
path = "/a/./b/../../c/", =>"/c"
整個過程:
l “/”根目錄
l “a”進入子目錄a,目前處於“/a”
l “.”當前目錄,不操作仍處於“/a”
l “/b”進入子目錄b,目前處於“/a/b”
l “..”返回上級目錄,處於“/a”
l “..”返回上級目錄,處於根目錄“/”
l “c”進入子目錄c,目前處於“/c”
利用棧解決問題:
把非'/'和'.'push進棧,如果遇到'..'出棧pop,否則壓棧push。最後還原成路徑格式。
【Python實現】
方法一:利用棧
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 5 13:32:23 2017
@author: Administrator
"""
class Solution(object):
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
stack = []
i = 0
res = ''
path_len = len(path)
while i < path_len:
j = i+1
while j < path_len and path[j] !="/":
j += 1
subpath = path[i+1:j]
if len(subpath) > 0:
if subpath == "..":
if stack != []:
stack.pop()
elif subpath != ".":
stack.append(subpath)
i = j
if stack == []:
return "/"
for character in stack:
res += "/"+ character
print(res)
return res
S = Solution()
S.simplifyPath("/a/./b/../../c/")
方法二:利用python的split()函數
class Solution:
#@param path, a string
#@return a string
def simplifyPath(self, path):
path = path.split('/')#將/作爲劃分標誌,轉化爲list ['', 'a', '.', 'b','..', '..', 'c', '']
curr = '/'
for character in path:
if character == '..':
if curr != '/':
curr ='/'.join(curr.split('/')[:-1])
if curr == '': curr = '/'
elif character != '.' andcharacter != '':
if curr != '/':
curr += '/' + character
else:
curr += character
print(curr)
return curr
S = Solution()
S.simplifyPath("/a/./b/../../c/")