See the original problem on HackerRank.
Given an absolute path for a file (Unix-style), simplify it.
This challenge simulates an interview problem. As you see, no more information about input constraints are provided. You - probably - have to interact with Marco (who impersonates the interviewer) and ask him some questions to refine your knowledge about the problem.
Only a string is provided.
The path always begins with ‘/’ (root directory).
The path simplified.
Hints
- are you sure you need the trailing
/
?
- you may be surprised but
/..
is valid
Solutions
A Javascript solution by Simone Busoli:
1
2
3
4
5
6
7
|
function processData(input) {
console.log('/' + input.split('/').reduce(([h, ...t] = [], f) => {
if (!f || f === '.') return [h, ...t]
if(f === '..') return [...t]
return [f, h, ...t]
}, []).reverse().join('/').replace(/^\/*/, '').replace(/\/*$/, ''))
}
|
A C++ solution by Alessandro Pezzato
using a stack (implemented by std::vector
).
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 <iostream>
#include <vector>
int main() {
std::vector<std::string> s;
std::string d;
while (std::cin) {
char c = std::cin.get();
if (c == '/' || c == '\n' || c == EOF) {
if (d == "..") {
if (!s.empty()) {
s.pop_back();
}
} else if (d != "." && !d.empty()) {
s.push_back(std::move(d));
}
d.clear();
} else {
d.push_back(c);
}
}
if (s.empty()) {
std::cout << "/";
} else {
for (auto t : s) {
std::cout << "/" << t;
}
}
}
|