Sharing my 8ms C++ solution


  • 0
    T
    class Solution {
    public:
        string simplifyPath(string path) {
            vector<string> dirs;
            int n=path.size();
            int start = 0;
            if(path[start]=='/')
            {
                start++;
                dirs.push_back("/");
            }
            
            int left, right, i;
            left=start;
            for(i=start; i<n; i++)
            {
                if(path[i] == '/')
                {
                    if(i==left)
                        left++;
                    else
                    {
                        dirs.push_back(path.substr(left, i-left));
                        left=i+1;
                    }
                }
            }
            if(path[n-1] != '/')
                dirs.push_back(path.substr(left, n));
            
            vector<string> effective;
            n = dirs.size();
            for(i=0; i<n; i++)
            {
                if(dirs[i] == ".")
                    continue;
                if(dirs[i] == ".." && effective.size()>1)
                    effective.pop_back();
                else if(dirs[i] != "..")
                    effective.push_back(dirs[i]);
            }
            
            n = effective.size();
            string s;
            for(i=1; i<n; i++)
                s = s + "/" + effective[i];
                
            if(s.length() == 0)
                return "/";
            return s;
        }
    };

Log in to reply
 

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