C++ solution without using stack


  • 0
    C
    class Solution {
    public:
        string simplifyPath(string path) {
            char *cstr = new char [path.size()+1];
            char *p;
            vector<char *>symbol;
            string res;
            strcpy(cstr, path.c_str());
            
            p = strtok(cstr, "/");
            while (p)
            {
                // p is not equal to "."
                if (strcmp(p, "."))
                {
                    // p is equal to ".."
                    if (!strcmp(p, ".."))
                    {
                        if (symbol.size() > 0)
                            symbol.pop_back();
                    }
                    else
                        symbol.push_back(p);
                
                }
                p = strtok(NULL, "/");
            }
            
            if (symbol.size() == 0)
                res = "/";
            else
            {
                for (int i = 0; i < symbol.size(); i++)
                {
                    string s(symbol[i]); 
                    res += "/"+s;
                }
            }
            delete[] cstr; 
            return res;
        }
    };

Log in to reply
 

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