-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
53 lines (45 loc) · 1.28 KB
/
main.cpp
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution {
public:
string simplifyPath(string path) {
path += "/";
regex slashes("//+");
path = regex_replace(path, slashes, "/");
vector<string> dirs;
for (int l = 0, r = path.find('/', l + 1); r != string::npos;
l = r, r = path.find('/', l + 1)) {
string dir = path.substr(l + 1, r - l - 1);
if (dir == ".") continue;
if (dir == "..") {
if (!dirs.empty()) dirs.pop_back();
continue;
}
dirs.push_back(dir);
}
if (dirs.empty()) return "/";
string result;
for (auto s : dirs) result += "/" + s;
return result;
}
};
class Solution {
public:
string simplifyPath(string path) {
vector<string> pathVec;
stringstream ss(path);
string p;
while (getline(ss, p, '/')) {
if (p == "" || p == "." || (pathVec.empty() && p == "..")) continue;
if (p == "..") {
pathVec.pop_back();
} else {
pathVec.push_back(p);
}
}
string result;
for (string& p : pathVec) {
result += "/";
result += p;
}
return result.empty() ? "/" : result;
}
};