Tokenize and keep a stack -- C++ code


  • 0
    G
        string simplifyPath(string path) {
            string c;
            stringstream ss_path(path);
            stack<string> s;
            while (getline(ss_path, c, '/')) {
                if (c == "." || c == "") {
                    continue;
                }
                if (c == "..") {
                    if (!s.empty()) {
                        s.pop();
                    }
                    continue;
                }
                s.push(c);
            }
            if (s.empty()) {
                return "/";
            }
            string r;
            while (!s.empty()) {
                r = "/" + s.top() + r;
                s.pop();
            }
            return r;
        }
    

Log in to reply
 

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