71. Simplify Path

problem

solution

先用split 切分成個字串,在判斷字串是否為”.” 或是 “..”

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
class Solution {
public:
vector<string> split(string str , char del ){
vector<string> ret;
string path ;
for(char c:str){
if(c==del){
if(!path.empty()) ret.push_back(path);
path="";
}
else path+=c;
}
if(!path.empty()) ret.push_back(path);
return ret;
}
string simplifyPath(string path) {
vector<string> str = split(path, '/');
vector<string> ans;
for(string tmp : str){
if(tmp.empty()) continue;
if(tmp == ".") continue;
else if(tmp ==".."){
if(!ans.empty()) ans.pop_back();
}
else ans.push_back(tmp);
}
string ret;
for(string c:ans) ret+="/"+c;
return ret.empty()?"/":ret;
}
};

analysis

  • time complexity O(n)
  • space complexity O(n)