Leetcode | 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".

这里用了一个vector来模拟栈。方便正序输出。

 

 1 class Solution {

 2 public:

 3     string simplifyPath(string path) {

 4         if (path.empty()) return "/";

 5         path.push_back('/');

 6         int start = -1, end;

 7         vector<string> st;

 8         while ((end = path.find('/', start + 1)) != string::npos) {

 9             string tmp = "";

10             if (end - start - 1) {

11                 tmp = path.substr(start + 1, end - start - 1);

12             }

13             if (tmp == ".." && !st.empty()) st.pop_back();

14             if (!tmp.empty() && tmp != "." && tmp != "..") st.push_back(tmp);

15             start = end;

16         }

17         stringstream ans;

18         for (int i = 0; i < st.size(); i++) {

19             ans << '/' << st[i];

20         }

21         if (!ans.str().empty()) return ans.str();

22         return "/";

23     }

24 };

 

你可能感兴趣的:(LeetCode)