Drill

ProblemsC++ › patterns

Tidy up a file path

hardpatternsStacksStringsParsingC++

A storage service is handed paths with stray slashes and dot segments in them, and stores exactly one canonical form.

tidyPath(raw: string) → string

C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

std::string tidyPath(std::string raw) {
    
}

Worked examples

CallResult
tidyPath(std::string("/home//user/"))std::string("/home/user")
tidyPath(std::string("/a/./b/../c"))std::string("/a/c")
tidyPath(std::string("/../"))std::string("/")
tidyPath(std::string("/"))std::string("/")

Hint

Split on the slash and push each real segment onto a stack; ".." pops instead. Joining the stack back up gives the answer.

Reference solution in C++
std::string tidyPath(std::string raw) {
    std::vector<std::string> kept;
    std::stringstream stream(raw);
    std::string part;
    while (std::getline(stream, part, '/')) {
        if (part.empty() || part == ".") continue;
        if (part == "..") {
            if (!kept.empty()) kept.pop_back();
        } else {
            kept.push_back(part);
        }
    }
    std::string result = "/";
    for (size_t i = 0; i < kept.size(); i++) {
        if (i > 0) result += "/";
        result += kept[i];
    }
    return result;
}

The same problem in another language

More patterns problems in C++