Simplify Path

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: Add an additional '/' at the end of 'path' for simply detecting the end.

 1 class Solution {
 2 public:
 3     string simplifyPath(string path) {
 4         string res;
 5         path += "/";
 6         size_t pos = path.find_first_of("/"), last = 0;
 7         while(pos != string::npos) {
 8             string s = path.substr(last, pos - last);
 9             if(s == "..") {
10                 if (!res.empty())
11                     res.resize(res.find_last_of("/"));
12             }
13             else if (!s.empty() && s != ".")
14             {
15                 res += "/";
16                 res += s;
17             }
18             last = pos + 1;
19             pos = path.find_first_of("/", last);
20         }
21         return res.empty() ? "/" : res;
22     }
23 };

 

 

posted @ 2014-04-24 02:45  beehard  阅读(144)  评论(0编辑  收藏  举报