-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path71. Simplify Path.cpp
More file actions
121 lines (117 loc) · 2.94 KB
/
71. Simplify Path.cpp
File metadata and controls
121 lines (117 loc) · 2.94 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
class Solution {
public:
string simplifyPath(string path)
{
deque<string> ds;
string ts = "/";
int flag = 0;
for (int i = 0; i < path.size(); i++)
{
if (flag == 0)
{
if (path[i] == '/')
{
//ts.push_back(path[i]);
flag = 1;
}
}
else if (flag == 1)
{
if (path[i] == '/')
continue;
else
{
ts.push_back(path[i]);
flag = 2;
}
}
else
{
if (path[i] == '/')
{
if (ts == "/..")
{
if (!ds.empty())
ds.pop_back();
}
else if (ts == "/.")
{
//
}
else
{
ds.push_back(ts);
}
ts = "/";
flag = 1;
}
else
{
ts.push_back(path[i]);
}
}
}
if (ts == "/..")
{
if (ds.empty())
return "/";
else
ds.pop_back();
}
else if (ts == "/.")
{
//
}
else if (ts != "/")
{
ds.push_back(ts);
}
if (ds.empty())
return "/";
else
{
string res = "";
while (!ds.empty())
{
res += ds.front();
ds.pop_front();
}
return res;
}
}
};
//version -2
class Solution
{
public:
string simplifyPath(string path)
{
stack<string> ss; // 记录路径名
for(int i = 0; i < path.size(); )
{
// 跳过斜线'/'
while(i < path.size() && '/' == path[i])
++ i;
// 记录路径名
string s = "";
while(i < path.size() && path[i] != '/')
s += path[i ++];
// 如果是".."则需要弹栈,否则入栈
if(".." == s && !ss.empty())
ss.pop();
else if(s != "" && s != "." && s != "..")
ss.push(s);
}
// 如果栈为空,说明为根目录,只有斜线'/'
if(ss.empty())
return "/";
// 逐个连接栈里的路径名
string s = "";
while(!ss.empty())
{
s = "/" + ss.top() + s;
ss.pop();
}
return s;
}
};