[AlgoExpert] Shorten Path

Shorten Path

  • Time : O(n)
  • Space : O(n)
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
using namespace std;

string parse(string& s, int& p) {
string res = "";
while(p < s.length() and s[p] != '/') {
res.push_back(s[p++]);
}
p++;
return res;
}

string shortenPath(string path) {
int i = 0;
bool root = path[0] == '/';
vector<string> st;
while(i < path.length()) {
auto dir = parse(path, i);
if(dir == "." or dir == "") continue;
else if(dir == "..") {
if(root) {
if(!st.empty()) st.pop_back();
} else {
if(!st.empty() and st.back() != "..") st.pop_back();
else st.push_back(dir);
}
} else st.push_back(dir);
}

string res = "";
for(auto& token : st)
res += token + '/';
if(res.length())
res.pop_back();
return root ? "/" + res : res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/10/PS/AlgoExpert/shorten-path/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.