[LeetCode] Simplify Path

Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/http://www.cnblogs.com/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".
用栈来做
 1 class Solution {
 2 public:
 3     string simplifyPath(string path) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         stack<string> s;
 7         string str;
 8         for(int i = 0; i < path.size(); i++)
 9         {
10             if (path[i] == '/')
11             {
12                 if (str == "..")
13                 {
14                     if (!s.empty())
15                         s.pop();
16                 }
17                 else if (str != "." && str != "")
18                 {
19                     s.push(str);
20                 }
21 
22                 str = "";
23             }
24             else
25             {
26                 str += path[i];
27             }
28         }
29         
30         if (str == "..")
31         {
32             if (!s.empty())
33                 s.pop();
34         }
35         else if (str != "." && str != "")
36             s.push(str);
37         
38         if (s.empty())
39             return "/";
40         
41         string ret;
42         while(!s.empty())
43         {
44             ret = "/" + s.top() + ret;
45             s.pop();
46         }
47         
48         return ret;
49     }
50 };
原文地址:https://www.cnblogs.com/chkkch/p/2778005.html