C++ solution with double ended queue


  • 0
    L

    here it goes

        deque<string> queue;
        string segment;
        for (int i = 0; i < path.length(); ++i) {
            char c = path[i];
            if (c == '/') {
                if (!segment.empty() && segment != "." && segment != "..") queue.push_back(segment);
                else if (segment == ".." && queue.size() > 0) queue.pop_back();
                segment.clear();
            }
            else {
                segment.push_back(c);
            }
        }
        if (!segment.empty() && segment != "." && segment != "..") queue.push_back(segment);
        else if (segment == ".." && queue.size() > 0) queue.pop_back();
    
        string outputStr;
        for (auto ptr = queue.cbegin(); ptr != queue.cend(); ptr++) {
            outputStr.push_back('/');
            outputStr.append((*ptr));
        }
        return outputStr.length() > 0 ? outputStr : "/";
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.