Description
Simplify Path Total Accepted: 10702 Total Submissions: 53877 My Submissions 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
The code with comments is quite self-explainable.
One thing worth noticing is that the “folder/file name” can have dot “.”, e.g.
\home\my.file\...
Code
Running Time: 72 ms
1 string simplifyPath(string path) {
2
3 vector<string>result_vec;
4
5 string tp = "";
6 for (int i = 0; i < path.size(); ++ i){
7 if (path[i] == '/'){ // slash
8 if (tp == ".." && result_vec.size())
9 result_vec.pop_back();
10 else if (tp.size() && tp != "." && tp != "..")
11 result_vec.push_back(tp);
12 tp = "";
13 }
14 else // letter or dot
15 tp += path[i];
16 }
17
18 if (tp == ".." && result_vec.size())
19 result_vec.pop_back();
20 else if (tp.size() && tp != "." && tp != "..")
21 result_vec.push_back(tp);
22
23 string result_str = (path[0] == '/')?"/":"";
24
25 for (int i = 0; i < result_vec.size(); ++ i)
26 result_str += result_vec[i] + "/";
27 cout << result_vec.size() << endl;
28 if (result_vec.size()) result_str.pop_back();
29 return result_str;
30 }