###### tags: `Leetcode` `medium` `string` `stack` `python`
# 71. Simplify Path
## [題目連結:] https://leetcode.com/problems/simplify-path/
## 題目:
Given a string path, which is an **absolute path** (starting with a slash ```'/'```) to a file or directory in a Unix-style file system, convert it to the simplified **canonical path**.
In a Unix-style file system, a period ```'.'``` refers to the current directory, a double period ```'..'``` refers to the directory up a level, and any multiple consecutive slashes (i.e. ```'//'```) are treated as a single slash ```'/'```. For this problem, any other format of periods such as ```'...'``` are treated as file/directory names.
The **canonical path** should have the following format:
* The path starts with a single slash '/'.
* Any two directories are separated by a single slash '/'.
* The path does not end with a trailing '/'.
* The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period '.' or double period '..')
Return the simplified **canonical path**.
**Example 1:**
```
Input: path = "/home/"
Output: "/home"
Explanation: Note that there is no trailing slash after the last directory name.
```
**Example 2:**
```
Input: path = "/../"
Output: "/"
Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
```
**Example 3:**
```
Input: path = "/home//foo/"
Output: "/home/foo"
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.
```
## 解題想法:
* 題目給一個絕對路徑:開頭'/',求轉換為canonical path
* in unix-style file:
* '.'表示當前目錄
* '..'表示上層目錄
* '//'連續多斜線,可視為單斜線'/'
* '...'多點視為目錄名稱
* canonical path:
* 開頭需有'/'(根目錄)
* 任何兩個目錄都由一個斜線'/'分隔。
* 結尾不需有'/'
* 該路徑僅包含從根目錄到目標文件或目錄的路徑上的目錄(即沒有'.'或'..')
* trace流程:
```
path="/a/./b/../../c/"
step1: 將path split by('/'): ['', 'a', '.', 'b', '..', '..', 'c', '']
step2: ''空格,忽略continue
step3: 'a'正常目錄,append到res
step4: '.'當前目錄,忽略continue
step5: 'b'正常目錄,append到res
step6: 連續兩個'..'上層再上層: 所以等於pop'b' 再 pop'a'
step7: 'c'正常目錄,append到res
最終開頭'/'+res中正常目錄(由"/'隔開)
return '/'+'/'.join(res)
```
## Python:
``` python=
class Solution(object):
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
res=[]
for char in path.split('/'): #split後type為list
if char=='' or char=='.':
continue
if char=='..':
if len(res)>0:
res.pop()
else:
res.append(char)
#'/'+res([a,b,c])= a/b/c
return '/'+'/'.join(res)
if __name__=='__main__':
result=Solution()
ans=result.simplifyPath(path="/a/./b/../../c/")
print(ans) # /c
```