C++ concise solution using stack, deque.


  • 1
    C
    string simplifyPath1(string path) {
        stack<string> myStack;
        istringstream ss(path);
        string str;
        while (getline(ss, str, '/')) 
            if (!str.empty()) {
                if (str == ".." && !myStack.empty())
                    myStack.pop();
                else if (str != "." && str != "..")
                    myStack.push(str);
            }
        string res = "";
        while (!myStack.empty()) {
            res = '/' + myStack.top() + res;
            myStack.pop();
        }
        return res.empty()?"/":res;
    }
    
    string simplifyPath(string path) {
        deque<string> myDeque;
        istringstream ss(path);
        string str;
        while (getline(ss, str, '/')) 
            if (!str.empty()) {
                if (str == ".." && !myDeque.empty())
                    myDeque.pop_back();
                else if (str != "." && str != "..")
                    myDeque.push_back(str);
            }
        string res = "";
        while (!myDeque.empty()) {
            res += "/" + myDeque.front();
            myDeque.pop_front();
        }
        return res.empty()?"/":res;
    }

Log in to reply
 

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