-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path71_simplify_path.cpp
More file actions
35 lines (30 loc) · 879 Bytes
/
71_simplify_path.cpp
File metadata and controls
35 lines (30 loc) · 879 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <sstream>
// NOTE: it's possible to optimize the algorithm by avoiding the stringstream
// construction and using the result string as a stack.
class Solution {
public:
string simplifyPath(string path) {
stack pathStack = stack<string>();
stringstream ss(path);
string node;
string result;
while(getline(ss, node, '/')) {
if (node == "" || node == ".")
continue;
if (node == ".."){
if (!pathStack.empty())
pathStack.pop();
continue;
}
pathStack.push(node);
}
while (!pathStack.empty()) {
result = "/" + pathStack.top() + result;
pathStack.pop();
}
if (result.size() == 0) {
return "/";
}
return result;
}
};