[LeetCode]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".
解题思路:
用栈。
 1 class Solution {
 2 public:
 3     string simplifyPath(string path) {
 4         vector<string> cache;
 5         for (auto i = path.begin(); i != path.end();) {
 6             ++i;
 7             auto j = find(i, path.end(), '/');
 8             auto sub = string(i, j);
 9             if (sub.size() > 0 && sub != ".") {
10                 if (sub == "..") {
11                     if (!cache.empty()) {
12                         cache.pop_back();
13                     }
14                 } else {
15                     cache.push_back(sub);
16                 }
17             }
18             i = j;
19         }
20         
21         
22         if (cache.empty()) {
23             return string("/");
24         }
25         
26         string result;
27         for (auto str : cache) {
28             result += "/";
29             result += str;
30         }
31         
32         return result;
33     }
34 };

 

 
posted @ 2015-11-17 14:43  skycore  阅读(149)  评论(0编辑  收藏  举报