// 演算法 / Algorithm:
// 用 stringstream + getline 以 '/' 切片，逐段處理：
// "" 與 "." 跳過，".." 對 vector pop_back，其餘 push_back，最後接成 "/a/b/c"。
// Tokenize on '/', skip ""/".", pop on "..", push otherwise, then join.

#include <string>
#include <vector>
#include <sstream>

class Solution {
public:
    std::string simplifyPath(std::string path) {
        std::vector<std::string> stack;       // 當作堆疊用的動態陣列 / vector used as a stack
        std::stringstream ss(path);           // 把 path 包成可讀的串流 / wrap path as a stream
        std::string token;                    // 每次取出的片段 / one segment per read

        // getline 以 '/' 為分隔符，一次讀出兩個 '/' 之間的內容
        // getline with '/' delimiter yields the text between two slashes.
        // 連續斜線會產生空字串 token，下面會被跳過。
        // Consecutive slashes yield empty tokens, skipped below.
        while (std::getline(ss, token, '/')) {
            if (token.empty() || token == ".") {
                // 空片段（連續斜線）或 "."（目前目錄）都忽略
                // empty token (multiple slashes) or "." (current dir): ignore
                continue;
            } else if (token == "..") {
                // 回到上一層：非空才 pop / go up: pop only if non-empty
                if (!stack.empty()) stack.pop_back();
            } else {
                // 合法目錄名，push 到尾端 / valid name, push to the back
                stack.push_back(token);
            }
        }

        // 組合結果：根目錄時為 "/"，否則 "/" + 每段用 '/' 連接
        // Build result: "/" for root, else each dir prefixed by '/'.
        std::string result;
        if (stack.empty()) return "/";        // 堆疊空 => 根目錄 / empty => root

        for (const std::string& dir : stack) { // range-for 逐一走訪 / range-for over each dir
            result += '/';                    // 先放一個分隔斜線 / one separating slash
            result += dir;                    // 再接目錄名 / then the directory name
        }
        return result;                        // 例如 "/home/user/Pictures"
    }
};
