71. Simplify Path

题目链接!

解题思路

  • 使用一个栈去存储每一条路径,如果是..就pop();
  • 注意处理边界//./..

代码

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
class Solution
{
public:
string simplifyPath(string path)
{
string res, temp;
res = temp = "";
stack<string> st;
int len = path.size();
for(int i = 0; i < len; ++i)
{
if(path[i] == '/')
{
if(temp == "" || temp == ".")
{
temp = "";
continue;
}
else if(temp == "..")
{
temp = "";
if(!st.empty())
st.pop();
}
else
{
st.push(temp);
temp = "";
}
}
else
{
temp += path[i];
}
}
if(temp != "")
{
if(temp == "..")
{
if(!st.empty())
st.pop();
}
else if(temp != ".")
st.push(temp);
}
if(st.empty())
return "/";
while(!st.empty())
{
res = "/" + st.top() + res;
st.pop();
}
return res;
}
};
-------------本文结束感谢您的阅读-------------
0%