Skip to content

Commit 08ed642

Browse files
Merge pull request #3247 from winfred-lu/main
Create 0071-simplify-path.cpp
2 parents ef903eb + ec32383 commit 08ed642

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

Diff for: cpp/0071-simplify-path.cpp

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/*
2+
Given an absolute path to a file or directory in a Unix-style file system,
3+
convert it to the simplified canonical path.
4+
5+
In a Unix-style file system, a period '.' refers to the current directory.
6+
A double period '..' refers to the directory up a level.
7+
Any multiple consecutive slashes (i.e. '//') are treated as a single slash '/'.
8+
For this problem, any other format of periods such as '...' are treated as file/directory names.
9+
10+
The canonical path should have the following format:
11+
- The path starts with a single slash '/'.
12+
- Any two directories are separated by a single slash '/'.
13+
- The path does not end with a trailing '/'.
14+
- The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period '.' or double period '..')
15+
16+
Return the simplified canonical path.
17+
18+
Time: O(n)
19+
Space: O(n)
20+
*/
21+
22+
class Solution {
23+
public:
24+
string simplifyPath(string path) {
25+
stringstream ss(path);
26+
string dir;
27+
stack<string> stk;
28+
29+
while (getline(ss, dir, '/')) {
30+
if (dir.empty() || dir == ".") {
31+
continue;
32+
}
33+
else if (dir == "..") {
34+
if (!stk.empty())
35+
stk.pop();
36+
}
37+
else {
38+
stk.push(dir);
39+
}
40+
}
41+
42+
string res = "";
43+
while (!stk.empty()) {
44+
res = "/" + stk.top() + res;
45+
stk.pop();
46+
}
47+
return res.empty()? "/" : res;
48+
}
49+
};

0 commit comments

Comments
 (0)