[Leetcode]Simplify Path

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

For example,
path = "/home/", => "/home"

path = "/a/./b/../../c/", => "/c"

class Solution {
public:
    /*algorithm
       for simplicity, for path--> "#"+path + "/"
        #/home/
        "#/../"
    */
    string simplifyPath(string path) {
        vector<string>paths;
        path = "#" + path +"/";
        int i = 0,j;
        while(i < path.size()){
            j = i;
            while(j < path.size() && path[j] != '/')++j;
            string dir = path.substr(i,j-i);
            if(dir == ".");
            else if(dir == ".."){
                if(paths.size() > 1)paths.pop_back(); //none root dir
            }else 
                paths.push_back(dir);     
            while(j < path.size() && path[j]=='/')++j; //skip duplicate slash
            i = j;
        }
        
        string sPath;;
        for(int i = 0;i < paths.size();i++){
            sPath += paths[i]=="#"?"":paths[i];
            if(i==0 || i+1<paths.size())sPath += "/";
        }
        return sPath;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章