Very Beautiful Code ! Simple to read [C++][Stack]


#1
string Solution::simplifyPath(string A) {
    stack<string>s;
    int i=0;
    while(i<A.size())
    {
        string c="";
        c+='/';
        int ind=i+1;
        while(ind<A.size())
        {
            if(ind==A.size()-1)
            {
                if(A[ind]!='/')
                    c+=A[ind];
                break;
            }
            if(A[ind]=='/' && A[ind+1]=='/')
            ind+=1;
            if(A[ind]=='/' && A[ind+1]!='/')break;
            c+=A[ind++];
        }
        i=ind;
        if(c=="/")break;
        if(c=="/.")continue;
        if(c=="/..")
        {
            if(!s.empty())
            {
                s.pop();
                continue;
            }
        }
        else
        {
            s.push(c);
        }
    }
    vector<string>ans;
    while(!s.empty())
    {
        ans.push_back(s.top());
        s.pop();
    }
    reverse(ans.begin(),ans.end());
    string ANS="";
    for(int i=0;i<ans.size();++i)
        ANS+=ans[i];
    if(ANS.empty())ANS+="/";
    return ANS;
}