[InterviewBit] Simplify Directory Path

Simplify Directory Path

  • Time :
  • Space :
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
vector<string> parse(string A) {
vector<string> res;
string now = "";
for(int i = 0; i < A.size(); i++) {
if(A[i] == '/') {
if(now.length()) res.push_back(now);
now = "";
} else now.push_back(A[i]);
}
if(now.length()) res.push_back(now);
return res;
}
string Solution::simplifyPath(string A) {
vector<string> token = parse(A);
vector<string> simple;
for(auto t : token) {
if(t == ".") continue;
else if(t == "..") {
if(!simple.empty()) simple.pop_back();
} else simple.push_back(t);
}
string res = "";
for(auto& s : simple) res += "/" + s;
return res == "" ? "/" : res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/16/PS/interviewbit/simplify-directory-path/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.