Skip to content

Latest commit

 

History

History
39 lines (34 loc) · 843 Bytes

78.md

File metadata and controls

39 lines (34 loc) · 843 Bytes

Simplify Path

LeetCode Link

string simplifyPath(string path) {
    stack<string> stk;
    stringstream ss(path);
    string token;

    while (getline(ss, token, '/')) {
        if (token == "" || token == ".") {
            continue;
        }
        if (token == "..") {
            if (!stk.empty()) {
                stk.pop();
            }
        } else {
            stk.push(token);
        }
    }

    vector<string> components;
    while (!stk.empty()) {
        components.push_back(stk.top());
        stk.pop();
    }
    reverse(components.begin(), components.end());

    string result = "/";
    for (const string& component : components) {
        result += component + "/";
    }

    if (result.size() > 1) {
        result.pop_back();
    }

    return result;
}