Wednesday, February 12, 2014

[leetcode][****] Simplify Path


Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
1. If the train of thought if not clear, this problem is hard.
2. /. does nothing;  /.. will get you back to the upper directory;
Algorithm:
1. delete the repeated "/".
2. add a "/" back to pair up all the "/"s.
3. only "/." and "/.." is considered seperatedly.
4. flag to mark the second "/" and handle the pop or push of stacks.
My Code:
  string simplifyPath(string path) {
       string ret = "";
       //erase "//"
       for(int i = path.length() - 1; i >=0; --i){
           if(path[i]==path[i+1] && path[i] == '/'){
               path.erase(i,1);
           }
       }
       //add "/" to the end to make sure "/" are in pairs
       if(path[path.length() - 1] != '/')
          path += '/';
       stack<string> cur;
       int flag = 0;
       string str = "";
       for(int i = 0; i < path.length(); ++i){
           if(path[i] == '/') ++flag;
           if(flag == 1) str += path[i];
           else if(flag == 2){
               if(str == "/.." && !cur.empty())
                    cur.pop();
               if(str != "/." && str!="/.." )
                    cur.push(str);
               flag = 1;
               str = "/";
           }
       }
       while(!cur.empty()){
            ret = cur.top()+ret;
            cur.pop();
       }
       if(ret.empty()) return "/";
       return ret;
    }

No comments:

Post a Comment