Cover image for Interview Classic 150 Questions P71 Simplify Path

Interview Classic 150 Questions P71 Simplify Path


Timeline

timeline

2025-11-18

init

stack

Title:

We need to distinguish between the first ‘/’ and the following ‘/’. The first is the root directory, the following are separators. Therefore, we can treat a directory as ‘/’ + ‘directory name’.

If the directory is “” (empty string), then it is the root directory.

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
#include <string>
#include <stack>
#include <sstream>
using std::string;
using std::stringstream;
using std::stack;

class Solution {
public:
string simplifyPath(string path)
{
string res, curr;
stringstream ss(path);
stack<string> st;
while (std::getline(ss, curr, '/')) {
if (curr.empty())
continue;
if (curr.compare("..") == 0) {
if (!st.empty())
st.pop();
else
continue;
} else if (curr.compare(".") == 0) {
continue;
} else {
st.push(curr);
}
}
while (!st.empty()) {
curr = st.top();
st.pop();
res.insert(0, curr);
res.insert(0, "/");
}
if (res.empty())
res = "/";
return res;
}
};