forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
simplify-path.cpp
48 lines (45 loc) · 1.35 KB
/
simplify-path.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
// Time: O(n)
// Space: O(n)
class Solution {
public:
/**
* @param path the original path
* @return the simplified path
*/
string simplifyPath(string& path) {
vector<string> names;
vector<string> tokens(move(split(path, '/')));
for (const auto& token : tokens) {
if (token == ".." && !names.empty()) {
names.pop_back();
} else if (token != ".." && token != "." && !token.empty()) {
names.emplace_back(token);
}
}
return string("/").append(join(names, '/'));
}
// Split string by delimitor.
vector<string> split(const string& s, const char delim) {
vector<string> tokens;
stringstream ss(s);
string token;
while (getline(ss, token, delim)) {
tokens.emplace_back(token);
}
return tokens;
}
// Join strings with delimitor.
string join(const vector<string>& names, const char& delim) {
string s;
if (!names.empty()) {
ostringstream ss;
string delim_str;
delim_str.insert(delim_str.begin(), delim);
copy(names.cbegin(), prev(names.cend()),
ostream_iterator<string>(ss, delim_str.c_str()));
ss << names.back();
s = ss.str();
}
return s;
}
};