Monday, October 28, 2013

Simplify Path [Leetcode]

Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

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".
Solution: the rules are as follows: 1. skip multiple '/'s; 2. when '.' is encountered, stay in the current folder; 3. when '..' is encountered, go back to the previous folder; 4. otherwise, go to the next level of folder.

class Solution {
public:
    string simplifyPath(string path) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        string ret;
        //invalid input check
        if(path.empty()||path[0]!='/')
            return ret;
        vector<string> p; //record the generated path until now
        int i=1;
        while(i<path.size()){
            //skip '/'
            if(path[i]=='/'){
                ++i;
                continue;
            }
            //collect the substring btwn two '/'
            string cur;
            while(path[i]!='/' && i<path.size()){
                cur+=path[i];
                i++;
            }
            if(cur==".") //stay in the current folder
                continue;
            else if(cur==".."){ //go back to previous folder
                if(!p.empty())
                    p.pop_back();
            }
            else // go further to the next level folder
                p.push_back(cur);
        }
        if(p.empty())
            return "/";
        //construct the path
        for(int i=0; i<p.size(); ++i){
            ret+="/";
            ret+=p[i];
        }
        return ret;
    }
};



No comments:

Post a Comment