LeetCode-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 {
public:
    string simplifyPath(string path) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        vector<string> ps;
        if(path=="")return "/";
        string p="";
        for(int i=0;i<path.length();i++){
            if(path[i]=='/'){
                if(p!="")ps.push_back(p);
                p.clear();
            }
            else{
                p+=path[i];
            }
            if(i+1==path.length()&&p!="")ps.push_back(p);
        }
        string ret="";
        stack<string> sta;
        for(int i=0;i<ps.size();i++){
            if(ps[i]==".."){
                if(sta.size()!=0)sta.pop();
            }
            else if(ps[i]=="."){
                
            }
            else{
                sta.push(ps[i]);
            }
        }
        while(sta.size()!=0){
            ret=sta.top()+"/"+ret;
            sta.pop();
        }
        ret="/"+ret;
        if(ret.size()==1)return ret;
        ret.resize(ret.size()-1);
        return ret;
    }
};
View Code
原文地址:https://www.cnblogs.com/superzrx/p/3357800.html