71. Simplify Path (Stack)

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

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

 

注意:题目中已限定是absolute path - contains the root directory and all other subdirectories in which a file or folder is contained.

class Solution {
public:
    string simplifyPath(string path) {
        stack<string> pathStack;
        string splitPath = path;
        string curPath;
        string ret="";
        int pos = 0;//absolute path, so path[0]=='/'
        while(pos!=string::npos && pos+1 < splitPath.length()){
            splitPath = splitPath.substr(pos+1); 
            pos = splitPath.find_first_of('/');
            if(pos!=0){ //ignore second '/'
                curPath = splitPath.substr(0,pos);
                
                if(curPath=="."){//ignore './'
                    
                }
                else if(curPath==".." ){ //ignore '/..'
                    if(!pathStack.empty()) pathStack.pop();
                }
                else{ //除了"."以及".."以外的都是文件名,比如"..."
                    pathStack.push(curPath);
                }
            }
        }
        
        if(pathStack.empty()) return "/";
        while(!pathStack.empty()){
            ret = "/" + pathStack.top() + ret;
            pathStack.pop();
        }
        return ret;
    }
};

 

posted on 2015-10-04 07:59  joannae  阅读(166)  评论(0编辑  收藏  举报

导航