@@ -27,41 +27,38 @@ class Solution {
27
27
return simplifyPath2 (path);
28
28
}
29
29
30
- string simplifyPath1 (string & path) {
30
+ string simplifyPath (string path) {
31
+ if (path.empty ()) return " /" ;
31
32
replace (begin (path), end (path), ' /' , ' ' );
32
33
vector<string> vs;
33
34
istringstream is (path);
34
35
string str;
35
36
while (is >> str) {
36
- if (str == " .." ) {
37
- if (!vs.empty ()) vs.pop_back ();
38
- continue ;
39
- }
40
- if (str != " ." ) vs.push_back (str);
37
+ if (str == " .." ) { if (!vs.empty ()) vs.pop_back (); }
38
+ else { if (str != " ." ) vs.push_back (str); }
41
39
}
42
40
if (vs.empty ()) return " /" ;
43
- string res ;
44
- for (auto s : vs) res += ( ' / ' + s) ;
45
- return res ;
41
+ ostringstream os ;
42
+ for (auto v : vs) os << " / " << v ;
43
+ return os. str () ;
46
44
}
47
45
48
46
string simplifyPath2 (string & path) {
49
- if (path.empty ()) return path ;
47
+ if (path.empty ()) return " / " ;
50
48
if (path.back () != ' /' ) path.push_back (' /' );
51
- int last = 0 ;
52
- for (int start = 0 , end = 0 ; end < path.size (); end++) {
49
+ int len = 0 ;
50
+ for (int begin = 0 , end = 0 ; end < path.size (); end++) {
53
51
if (path[end] != ' /' ) continue ;
54
- if (end - start == 3 && path[end - 1 ] == ' .' && path[end - 2 ] == ' .' ) {
55
- while (last > 0 && path[--last] != ' /' );
52
+ if (end - begin == 3 && path[end - 2 ] == ' .' && path[end - 1 ] == ' .' ) {
53
+ if (len > 0 ) len--;
54
+ while (len > 0 && path[len] != ' /' ) len--;
56
55
}
57
- else if (end - start > 2 || (end - start == 2 && path[end - 1 ] != ' .' )) {
58
- while (start < end) path[last ++] = path[start ++];
56
+ else if (end - begin > 2 || (end - begin == 2 && path[end - 1 ] != ' .' )) {
57
+ while (begin < end) path[len ++] = path[begin ++];
59
58
}
60
- start = end;
59
+ begin = end;
61
60
}
62
-
63
- if (last == 0 ) return " /" ;
64
- return path.substr (0 , last);
61
+ return len == 0 ? " /" : path.substr (0 , len);
65
62
}
66
63
};
67
64
0 commit comments