The thinking of just simply simulate the simplify process using stack


  • 0
    J
    class Solution {
    public:
    string simplifyPath(string path) {
        stack<string>paths;
        int last=0;
        int cur=0;
        while(cur<path.size())
        {
            if(path[cur]!='/')
            {
                cur++;
                continue;
            }
            if(cur!=last)
            {
                int len=cur-last;
                string subStr=path.substr(last+1,len-1);
                if(subStr==".")
                    ;
                else if(subStr=="..")
                {
                    if(!paths.empty())
                        paths.pop();
                }
                else if(subStr!="")
                    paths.push(subStr);
                last=cur;
            }
            cur++;
        }
        if(last!=path.size()-1)
        {
            string subStr=path.substr(last+1);
            if(subStr==".")
                ;
            else if(subStr=="..")
            {
                if(!paths.empty())
                    paths.pop();
            }
            else if(subStr!="")
                paths.push(subStr);
        }
        
        string res="";
        while(!paths.empty())
        {
            string t=paths.top();
            if(res=="")
                res=t;
            else
                res=t+"/"+res;
            paths.pop();
        }
        return "/"+res;
    }};

Log in to reply
 

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