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".

模拟栈

/*
1.遇到./,当前位置-2,
2.遇到../,当前位置-3,然后回退到上一个斜杠处
测试用例:
.
..
/.
/..
/...
/./
/../
///
/./
/../
/.../
/..../../../../../../
/a../././../
/a.../././..
*/
class Solution {
public:
    string simplifyPath(string path) {
        int i=0,j=0;
        if(path.size()>0){
            path.push_back('/');
        }
        string res(path.size(),' ');
        while(i<path.size()){
            if(i>0 && path[i]==res[j-1] && path[i]=='/') {
                i++;
                continue;
            }
            res[j++] = path[i];
            if(path[i]=='/'){
                int pre_level_start = i-3>=0? i-3:0;
                if(path.substr(pre_level_start,i-pre_level_start+1)=="/../"){
                    j-=4;
                    while(j-1>=0 && res[j-1]!='/') --j;
                    if(j==0){
                        j=1;
                    }
                }else{
                    pre_level_start = i-2>=0? i-2:0;
                    if(path.substr(pre_level_start,i-pre_level_start+1)=="/./"){
                        j-=2;
                    }
                }
            }
            i++;
        }
        if(j>1 && res[j-1]=='/') --j;
        res.erase(res.begin()+j,res.end());
        return res;
    }
};
原文地址:https://www.cnblogs.com/zengzy/p/5040096.html