-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimplify_path.cpp
More file actions
86 lines (81 loc) · 2.04 KB
/
simplify_path.cpp
File metadata and controls
86 lines (81 loc) · 2.04 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
/*
* =====================================================================================
*
* Filename: simplify_path.cpp
*
* Description: 71. Simplify Path. Given an absolute path for a file (Unix-style),
* simplify it. Or in other words, convert it to the canonical path.
*
* Version: 1.0
* Created: 04/11/19 10:39:34
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
class Solution
{
public:
std::string simplifyPath(const std::string& path)
{
std::vector<std::string> nodes;
size_t idx = 0;
while (idx < path.size())
{
size_t pos = path.find('/', idx);
std::string sub;
if (pos == std::string::npos)
{
sub = path.substr(idx);
}
else
{
sub = path.substr(idx, pos - idx);
}
if (sub.empty() || sub == ".")
{
; // Ignore
}
else if (sub == "..")
{
if (!nodes.empty())
{
nodes.pop_back();
}
}
else
{
nodes.push_back(sub);
}
if (pos == std::string::npos)
{
break;
}
idx = pos + 1;
}
std::string simp_path;
for (const auto& item: nodes)
{
simp_path += "/" + item;
}
if (simp_path.empty())
{
simp_path = "/";
}
return simp_path;
}
};
int main(int argc, char* argv[])
{
std::string path = "/a//b////c/d//././/..";
auto simp_path = Solution().simplifyPath(path);
printf("Simplify path: %s\n", simp_path.c_str());
return 0;
}