程式語言 - LeetCode - C++ - 71. Simplify Path



題目:


解答:

class Solution {
public:
    string simplifyPath(string path) {
        stringstream ss(path);
        string token;
        vector<string> q;

        while (getline(ss, token, '/')) {
            if (token == "" || token == ".") {
                continue;
            }
            else if (token == "..") {
                if (!q.empty()) {
                    q.pop_back();
                }
            }
            else {
                q.push_back(token);
            }
        }

        string ans;
        for (auto& s : q) {
            ans += "/" + s;
        }

        return ans.empty() ? "/" : ans;
    }
};