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".
 
Runtime: 6ms
 1 class Solution {
 2 public:
 3     string simplifyPath(string path) {
 4         string newPath;
 5         vector<string> directory;
 6         stringstream newString(path);
 7         string temp;
 8         while (getline(newString, temp, '/')) {
 9             if (temp == "." || temp == "") continue;
10             else if (temp == ".." && !directory.empty()) directory.pop_back();
11             else if (temp != "..") directory.push_back(temp);
12         }
13         
14         for (string current : directory) {
15             newPath += "/" + current;
16         }
17         return newPath.empty() ? "/" : newPath;
18     }
19 };

 

posted @ 2016-09-29 11:08  amazingzoe  阅读(110)  评论(0)    收藏  举报