---
# System prepended metadata

title: Leetcode 71 Simplify Path
tags: [Leetcode, 程式菜雞的coding日常]

---

# Leetcode 71 Simplify Path
###### tags: `Leetcode` `程式菜雞的coding日常`
## 題目原文
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.

## 題目理解
將Unix形式的路徑簡化。
以'/'開始，兩個directory中間會以一個'/'分開，結尾不會有'/'，並且簡化後的路徑只有從起點到終點的路徑。
其餘指令:
* /./代表停在原地
* /../代表往回一層
* 多個'/'(如////)當作跟只有一個/一樣


## 解題思路
利用類似stack的概念來做出最短路徑。
先利用stringstraem將字串做分離，再根據條件決定要push還是pop，最後再輸出就可以了。

## 程式實作
```cpp=
class Solution {
public:
    string simplifyPath(string path) {
        vector<string> file;
        string ans = "",tmp;
        stringstream ss(path);

        while(getline(ss,tmp,'/')){
            if(!file.empty() && tmp == ".."){
                file.pop_back();
            }else if(tmp != "." && tmp != ".." && tmp != ""){
                file.push_back(tmp);
            }
        }

        for(string s:file){
            ans += "/" + s;
        }
        return ans.empty() ? "/":ans;
    }
};
```

## 後記
2023/4/12的daily challenge
剛說要努力日更結果第二天就忘記了，笑死