Simplify Path

Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

click to show corner cases.

Corner Cases:

  • Did you consider the case where path = "/../"?
    In this case, you should return "/".
  • Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
    In this case, you should ignore redundant slashes and return "/home/foo".
class  Solution {
private:
     int index;
     string path;
     string getpath()
    {
        index++;
         string newpath= "";
         while(index<path.length() && path[index]!= ' / ')
        {
            newpath=newpath+path[index];
            index++;            
        }
         return newpath;
    }
public:
     string simplifyPath( string path) 
    {
         this->path=path;
        stack< string> stk;
        index= 0;
         while(index<path.size())
        {
             string newpath=getpath();
             if(newpath== " .. ")
            {
                 if(stk.empty()== false)
                    stk.pop();
                 continue;
            }
             if(newpath== " . " || newpath== ""continue;
            stk.push(newpath);
        }
         string result= "";
         while(stk.empty()== false)
        {
            result= ' / '+stk.top()+result;
            stk.pop();
        }
         if(result.length()== 0) result= " / ";
         return result;
    }
};

你可能感兴趣的:(Path)