跳转至

简化路径⚓︎

Leetcode题目链接

描述⚓︎

详见中文题目链接

解答⚓︎

class Solution {
public:
    string simplifyPath(string path) {
        auto split = [](const string& s, char delimiter) -> vector<string> {
            vector<string> res;

            string curr;
            for (const char& ch : s) {
                if (ch == delimiter) {
                    res.emplace_back(curr);
                    curr.clear();
                } else {
                    curr += ch;
                }
            }

            res.emplace_back(curr);
            return res;
        };

        vector<string> names = split(path, '/');
        vector<string> stk;
        for (string& name : names) {
            if (name == "..") {
                if (!stk.empty()) stk.pop_back();
            } else if (!name.empty() && name != ".") {
                stk.emplace_back(name);
            }
        }

        string res;
        if (stk.empty()) {
            res = "/";
        } else {
            for (string& name : stk) {
                res += "/" + name;
            }
        }
        return res;
    }
};