Skip to content

Commit dfd3e66

Browse files
committed
路径-》 栈的巧妙处理
1 parent 327791a commit dfd3e66

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

string/Simply Path

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// g关键是要知道unix的路径知识,然后就是栈的数据结构
2+
3+
class Solution {
4+
public:
5+
string simplifyPath(string path) {
6+
string result;
7+
vector<string> dirs;// 这里不用真正的栈是因为最后输出还是从前到后的
8+
for (auto iter = path.begin();iter != path.end();/*++iter*/)
9+
{
10+
++iter;// 从第二个开始,因为第一个肯定是/
11+
auto pos = find(iter,path.end(),'/');// 用这个返回的是iterator ,用 string.find() 返回的是size_t
12+
string dir = string(iter,pos);// 字符串构造方式,[first,last) 当first= last,dir =""
13+
if (!dir.empty() && dir != ".")
14+
{
15+
if(dir == "..")
16+
{
17+
if(!dirs.empty())
18+
dirs.pop_back();
19+
}
20+
else
21+
dirs.push_back(dir);
22+
}
23+
iter = pos;// 这里iter 有个赋值,所以要先判断条件,而不能直接iter++
24+
}
25+
if(dirs.empty())
26+
result = "/";
27+
else
28+
{
29+
for(auto s:dirs)
30+
result += "/" + s;
31+
}
32+
return result;
33+
}
34+
};

0 commit comments

Comments
 (0)