Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
,
=> "/home"
path = "/a/./b/../../c/"
,
=> "/c"
"/../"
?"/"
.‘/‘
together, such
as "/home//foo/"
."/home/foo"
.
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
37
38
39
40
41
42
43
44
45
46
47 |
class
Solution { public : string simplifyPath(string path) { string re = "" ; stack <string > sk; int
i = 0; int
len = path.length(); while (i<len) { if (path[i] == ‘/‘ ) { i++; continue ; } int
j = 0; while (i+j < len && path[i+j]!= ‘/‘ )j++; string temp = path.substr(i,j); if (temp == ".." ) { if (!sk.empty()) sk.pop(); i = i+2; } else
if (temp == "." ){ i++; continue ; } else { i = i +j; sk.push(temp); } } if (sk.empty()) return
"/" ; while (!sk.empty()) { string temp = sk.top(); re = ‘/‘
+ temp + re; sk.pop(); } return
re; } }; |
原文:http://www.cnblogs.com/pengyu2003/p/3596269.html